Query selector with body but not on id in javascript

Viewed 1591

I got stuck with the elements selecting whole body but not particular id in that body. I tried the following things for the javascript

 var boxElemb =  document.querySelector("body:not('ul#id')");
    boxElemb.innerHTML=boxElemb.innerHTML.replace(/BOTÕES/g, 'Puxadores');

But it does not work. I am replacing the content with another text. Please help me out if any one has the solution

4 Answers

ul#id inside not is not a valid syntax.

Use [id]. Anything between [ and ] will be treated as attribute. You can also filter it using attribute value like [id='myId'].

document.querySelector("body:not('ul[id]')");

You can select all the body, and then remove the unnecessary ul. Like this:

var body = document.querySelector("body");
var ul = document.getElementById("your-id");
body.removeChild(ul);

That is in case your ul is the direct child of the body element, otherwise, you will need to adjust it.

You can replace your Text in all the body, then in specific id replace it back

const body =  document.querySelector("body");
const id = document.querySelector("#id");
body.innerHTML=boxElemb.innerHTML.replace(/BOTÕES/g,'Puxadores');
id.innerHTML=boxElemb.innerHTML.replace('Puxadores', /BOTÕES/g);

If you say the tabbing is not working if you change the text, then you are missing something else altogether. However, the below should work as per your requirement: change everywhere except for ul with a specific id

var body = document.querySelector('body'),
    ulIdText = document.querySelector('ul#id').innerHtml,
    bodyText = body.innerHTML
                 .replace(ulIdText,'_^_preallocatedtext_^_') 
                 .replace(/BOTÕES/g,'Puxadores')
                 .replace('_^_preallocatedtext_^_',ulIdText);

body.innerHTML = bodyText;

You can get rid of unnecessary variables here, but I advise to keep it this way so it is self-explanatory for revisiting later on.

The difference here compared to the other two answers

  1. the entire HTML is fully formed before replacing the existing HTML.
  2. body:not doesn't exclude the not part as body doesn't contain the exclusions in its tags/attributes. You'd need to use document.querySelectorAll but that'll require a huge loop.
Related