Your comments on various answers suggest your HTML is invalid and has more than one id="adsensebanner"
in it, but just one id="ad"
in it.
Your best bet is to make the HTML valid. There can be only one element with id="adsensebanner"
in it.
However, if for some reason you want to only target that one element when it's inside id="ad"
:
document.querySelector("#ad #adsensebanner").classList.add("addedclass");
or with jQuery:
$("#ad #adsensebanner").addClass("addedclass");
That says "Add 'addedclass' to #adsensebanner
only if it's inside #ad
." There can be valid use-cases (if the one element with id="adsensebanner"
may or may not be within #ad
and you don't want to add the class if not), but they're rare.
If you correct the HTML to only have one id="adsensebanner"
, and you always want to add the class, then:
document.getElementById("adsensebanner").classList.add("addedclass");
or with jQuery:
$("#adsensebanner").addClass("addedclass");
In a comment you've said:
The double division check will definately work, however, my second div's ID name varies, so I would like to have it selected via an attr, like div[id*='adsensebanner']
. Is there any workaround for this?
Yes, you can use any of the attribute substring selectors. For instance, if the id
will always start with adsensebanner
(id="adsensebanner1"
, id="adsensebanner2"
, etc.), then the selector to use with querySelector
or jQuery would be "#ad div[id^=adsensebanner]"
. (Or you can use the contains one you mentioned, *=
, or $=
if it always ends with something.)