Tuesday, 15 March 2011

How to add class to target nodes in javascript? -



How to add class to target nodes in javascript? -

i want create external link background yellowish adding class = 'external' them, don't know how accomplish that. please help? how identify external link , how add together class them accordingly?

<style> .external { background-color: yellowish } </style> <ul> <li><a href="http://google.com">http://google.com</a></li> <li><a href="/tutorial">/tutorial.html</a></li> <li> <a href="ftp://ftp.com/file.zip">ftp://ftp.com/file.zip</a> </li> <li><a href="http://nodejs.org">http://nodejs.org</a></li> </ul>

the result should this:

one approach:

class="snippet-code-js lang-js prettyprint-override">// utilize array.prototype.foreach iterate on elements returned // document.queryselectorall('li a'): array.prototype.foreach.call(document.queryselectorall('li a'), function (aelem) { // if hostname of <a> element not same hostname of // of current window: if (aelem.hostname !== window.location.hostname) { // can add together 'external' class-name element's classlist: aelem.classlist.add('external'); } }); class="snippet-code-css lang-css prettyprint-override">.external { background-color: #ffa; } class="snippet-code-html lang-html prettyprint-override"><ul> <li><a href="http://google.com">http://google.com</a></li> <li><a href="/tutorial">/tutorial.html</a></li> <li> <a href="ftp://ftp.com/file.zip">ftp://ftp.com/file.zip</a> </li> <li><a href="http://nodejs.org">http://nodejs.org</a></li> </ul>

slightly more concisely, skip if (...) , utilize classlist.toggle(classname, boolean) in foreach():

class="snippet-code-js lang-js prettyprint-override">// utilize array.prototype.foreach iterate on elements returned // document.queryselectorall('li a'): array.prototype.foreach.call(document.queryselectorall('li a'), function (aelem) { // if switch ('aelem.hostname !== window.location.hostname') evaluates // true: add together supplied classname, if it's // false: remove classname: aelem.classlist.toggle('external', aelem.hostname !== window.location.hostname); }); class="snippet-code-css lang-css prettyprint-override">.external { background-color: #ffa; } class="snippet-code-html lang-html prettyprint-override"><ul> <li><a href="http://google.com">http://google.com</a></li> <li><a href="/tutorial">/tutorial.html</a></li> <li> <a href="ftp://ftp.com/file.zip">ftp://ftp.com/file.zip</a> </li> <li><a href="http://nodejs.org">http://nodejs.org</a></li> </ul> references:

array.prototype.foreach(). element.classlist. function.prototype.call(). urlutils.hostname.

javascript

No comments:

Post a Comment