Skip to content Skip to sidebar Skip to footer

Editing A Class With Jquery

So as weird as this sounds I have a full url as a class for some of my html elements. Obviously this doesn't work for css puposes. What I am looking to do is remove every thing exc

Solution 1:

This does just what you are attempting:

var items = document.querySelectorAll("li.menu-item");
alert(items.length + " items with classes that need to be changed found.");

for(var i = 0 ; i < items.length; ++i){
   var classes = items[i].className.split(" ");
   items[i].className = classes[0] + " " + classes[1].split("/")[3];
   alert("New class attribute value is: " + items[i].className);
}
.menu-item { font-family:Arial; font-size:1.5em; }
.page-link { background-color: red; }
.something {background-color: green;}
.go-somewhere {background-color: yellow; }
<li class="menu-item http://example.com/page-link/">some code</li>
<li class="menu-item http://example.com/something/">some code</li>
<li class="http://example.com/go-somewhere/">some code</li>
<li class="menu-item http://example.com/go-somewhere/">some code</li>

Solution 2:

var strclass = "menu-item http://example.com/page-link/";
var newclass = strclass.replace("http\:\/\/.+\/(.+)\/", "$1");

Now I don't know if this would solve all your problems, but it sounds like you're just being too specific. Just make a more generic expression, and replace that part of the class string.

If you want something a bit less greedy, to only get the last folder

var newclass = strclass.replace("http\:\/\/.+\/([^\/]+)\/", "$1");

Solution 3:

You can use the slashes to build an array:

url = url.split("/");

Then get the slug which will be either the last or the second to last element in the array depending on if there is a trailing / or not.

if (url[url.length - 1]) {
  slug = url[url.length - 1];
} else {
  slug = url[url.length - 2];
}

Solution 4:

I'd probably use this regex with a replace: /.*?([^/]+)\/?$/

$('li[class*="http://"]').each(function(){
  var pattern = new RegExp('^https?://');
  var classes = this.className.split(' ');
  for(var i = 0, len = classes.length; i < len; i++) {
    if(pattern.test(classes[i])) {
      classes[i] = classes[i].replace(/.*?([^/]+)\/?$/, '$1');
    }
  }
  this.className = classes.join(' ');
});
.page-link {color: green;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<li class="menu-item http://example.com/page-link/">some code</li>
<li class="menu-item http://example.com/page-link/">some code</li>
<li class="menu-item http://example.com/page-link/">some code</li>

Note that my solution has a regex that tests against both http and https (excluding the //example.com/whatever/ syntax and relative urls), but the jQuery selector only grabs the http linked list items. You probably should create a class for this. Something like linked-list-item or whatever.


Post a Comment for "Editing A Class With Jquery"