Change from getElementById to getElementsByClassName [duplicate] - javascript

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 7 years ago.
Hi i got a script like this:
$(".news-button").click(function(){
var img = document.getElementById('news-image').src;
if (img.indexOf('news-bt-1.png')!=-1) {
document.getElementById('news-image').src = 'img/news-bt-2.png';
}
else {
document.getElementById('news-image').src = 'img/news-bt-1.png';
}
});
It worked fine but now i want to change news-image from id to class so how to change the code above?

You can use getElementsByClassName instead getElementById

You can use getElementsByClassName and select the first element, because this method returns a list of Elements which is ordered by the position of the elements in the DOM.
So, given that the element you want to get is the first one that appears in your HTML code with that class, you can do:
document.getElementsByClassName("news-image")[0]
And if it isn't the first one, you can change the number and select another element:
document.getElementsByClassName("news-image")[2] // third element
You can also use querySelector to select the first element that matches the given CSS selector, which is, in my opinion, easier:
document.querySelector("img.news-image")
Finally, since I see you're using jQuery as well, you can use it's selector like this:
$("img.news-image")[0]
Talking about your specific code, here's the solution you were looking for:
$(".news-button").click(function(){
var img = $('img.news-image')[0];
if (img.src.indexOf('news-bt-1.png')!=-1) {
img.src = 'img/news-bt-2.png';
}
else {
img.src = 'img/news-bt-1.png';
}
});

You can use
var elements = document.getElementsByClassName(classname)
It will get you all the elements matched as an array. So first make sure you got the array, then access the elements like elements[index]

Use :-
document.getElementsByClassName('news-image')[0].src
Since getElementsByClassName returns array you need to use index of it.
But as i can see you are using jquery on click event then why you are using javascript inside it instead use jquery inside it will help you in cross-platform
$(".news-image").each( function() {
var img= $(this).attr('src');
if (img.indexOf('news-bt-1.png')!=-1) {
$(this).attr('src','img/news-bt-2.png')
}else{
$(this).attr('src','img/news-bt-1.png')
}
});

Use the below code, just Replace className with the actual class name of you tag img :
$(".news-button").click(function () {
var img = document.getElementById('news-image').src;
var img1 = document.getElementsByClassName("className");
if (img.indexOf('news-bt-1.png') != -1) {
img1.src = 'img/news-bt-2.png';
}
else {
img1.src = 'img/news-bt-1.png';
}
});

You can use Jquery as well.
To get source of image:
$('.classname').attr('src')

Related

Traversing elements in javaScript

I need to change the href of link in a box. I can only use native javaScript. Somehow I have problems traversing through the elements in order to match the correct <a> tag.
Since all the a tags inside this container are identical except for their href value, I need to use this value to get a match.
So far I have tried with this:
var box = document.getElementsByClassName('ic-Login-confirmation__content');
var terms = box.querySelectorAll('a');
if (typeof(box) != 'undefined' && box != null) {
for (var i = 0; i < terms.length; i++) {
if (terms[i].href.toLowerCase() == 'http://www.myweb.net/2/') {
terms[i].setAttribute('href', 'http://newlink.com');
}
}
}
However, I keep getting "Uncaught TypeError: box.querySelectorAll is not a function". What do I need to do in order to make this work?
Jsfiddle here.
The beauty of querySelectorAll is you dont need to traverse like that - just use
var terms = document.querySelectorAll('.ic-Login-confirmation__content a');
And then iterate those. Updated fiddle: https://jsfiddle.net/4y6k8g4g/2/
In fact, this whole thing can be much simpler
var terms = document.querySelectorAll('.ic-Login-confirmation__content a[href="http://www.myweb.net/2/"]');
if(terms.length){
terms[0].setAttribute('href', 'http://newlink.com');
}
Live example: https://jsfiddle.net/4y6k8g4g/4/
Try This:
var box = document.getElementsByClassName('ic-Login-confirmation__content')[0];
Since you are using getElementsByClassName ,it will return an array of elements.
The getElementsByClassName method returns returns a collection of all elements in the document with the specified class name, as a NodeList object.
You need to specify it as follows for this instance:
document.getElementsByClassName('ic-Login-confirmation__content')[0]
This will ensure that you are accessing the correct node in your HTML. If you console.log the box variable in your example you will see an array returned.
you can select by href attr with querySelector,
try this:
document.querySelector('a[href="http://www.myweb.net/2/"]')
instead of defining the exact href attribute you can simplify it even more :
document.querySelector('a[href?="myweb.net/2/"]'
matches only elments with href attribute that end with "myweb.net/2/"

remove everything that is inside the actual tag [duplicate]

Is it possible to remove all attributes at once using jQuery?
<img src="example.jpg" width="100" height="100">
to
<img>
I tried $('img').removeAttr('*'); with no luck. Anyone?
A simple method that doesn't require JQuery:
while(elem.attributes.length > 0)
elem.removeAttribute(elem.attributes[0].name);
Update: the previous method works in IE8 but not in IE8 compatibility mode and previous versions of IE. So here is a version that does and uses jQuery to remove the attributes as it does a better job of it:
$("img").each(function() {
// first copy the attributes to remove
// if we don't do this it causes problems
// iterating over the array we're removing
// elements from
var attributes = $.map(this.attributes, function(item) {
return item.name;
});
// now use jQuery to remove the attributes
var img = $(this);
$.each(attributes, function(i, item) {
img.removeAttr(item);
});
});
Of course you could make a plug-in out of it:
jQuery.fn.removeAttributes = function() {
return this.each(function() {
var attributes = $.map(this.attributes, function(item) {
return item.name;
});
var img = $(this);
$.each(attributes, function(i, item) {
img.removeAttr(item);
});
});
}
and then do:
$("img").removeAttributes();
One-liner, no jQuery needed:
[...elem.attributes].forEach(attr => elem.removeAttribute(attr.name));
Instead of creating a new jQuery.fn.removeAttributes (demonstrated in the accepted answer) you can extend jQuery's existing .removeAttr() method making it accept zero parameters to remove all attributes from each element in a set:
var removeAttr = jQuery.fn.removeAttr;
jQuery.fn.removeAttr = function() {
if (!arguments.length) {
this.each(function() {
// Looping attributes array in reverse direction
// to avoid skipping items due to the changing length
// when removing them on every iteration.
for (var i = this.attributes.length -1; i >= 0 ; i--) {
jQuery(this).removeAttr(this.attributes[i].name);
}
});
return this;
}
return removeAttr.apply(this, arguments);
};
Now you can call .removeAttr() without parameters to remove all attributes from the element:
$('img').removeAttr();
One very good reason to do this for specific tags is to clean up legacy content and also enforce standards.
Let's say, for example, you wanted to remove legacy attributes, or limit damage caused by FONT tag attributes by stripping them.
I've tried several methods to achieve this and none, including the example above, work as desired.
Example 1: Replace all FONT tags with the contained textual content.
This would be the perfect solution but as of v1.6.2 has ceased to function. :(
$('#content font').each(function(i) {
$(this).replaceWith($(this).text());
});
Example 2: Strip all attributes from a named tag - e.g. FONT.
Again, this fails to function but am sure it used to work once upon a previous jQuery version.
$("font").each(function() {
// First copy the attributes to remove.
var attributes = $.map(this.attributes, function(item) {
return item.name;
});
// Now remove the attributes
var font = $(this);
$.each(attributes, function(i, item) {
$("font").removeAttr(item);
});
});
Looking forward to 1.7 which promises to include a method to remove multiple attributes by name.
One-liner.
For jQuery users
$('img').removeAttr(Object.values($('img').get(0).attributes).map(attr => attr.name).join(' '));
One don't need to refer to the name of attribute to to id nowadays, since we have
removeAttributeNode method.
while(elem.attributes.length > 0) {
elem.removeAttributeNode(elem.attributes[0]);
}
I don't know exactly what you're using it for, but have you considered using css classes instead and toggling those ? It'll be less coding on your side and less work for the browser to do. This will probably not work [easily] if you're generating some of the attributes on the fly like with and height.
This will remove all attributes and it will work for every type of element.
var x = document.createElement($("#some_id").prop("tagName"));
$(x).insertAfter($("#some_id"));
$("#some_id").remove();
Today I have same issue. I think that it will be useful for you
var clone = $(node).html();
clone = $('<tr>'+ clone +'</tr>');
clone.addClass('tmcRow');

How to use jquery to get one of the class name attribute of an html element which has multiple class names assigned [duplicate]

This question already has answers here:
jQuery - get the first class only from a element
(3 answers)
Closed 9 years ago.
For example:
<div class="home current">home</div>
When I use $(this).attr("class"), it simply returns "home current".
I want to get the "home" attribute only. How can I achieve this?
If you know the class name and want to check if an element has it, you can use .hasClass()
// will return true if the element has that class applied to it
$(elem).hasClass('home');
On the other hand, if you want each class applied to an element separately, you can split by space and iterate:
var classes = $(elem).attr('class').split(' ');
for(var i=0; i<classes.length; i++) {
classes[i]; // each class name
}
The class attribute returns the space delimitered list of css classes assigned to the element, to convert this into an array use the split method on the string, and to retrieve the first one, use the [0] indexer, as in:
var firstClass = $(this).attr('class').split(' ')[0]
var allClass= $(this).attr("class");
var class = allClass.replace("current", "");
this will work if you only have "current" as an additional class
Is there a specific reason that you need to pull the class list. If you know the class you are looking for and just need to check if the object has the class home, you could do this:
$(this).hasClass("home");
Otherwise, you could just split the result and check for whatever class you need.
var classAttr = $(this).attr("class");
var classes = classAttr.split(" ");
It seems you need the primary class of the element.
var primaryClass= $(this).attr('class').split(' ')[0].
Remember this line may cause exception if no class applied,while the time you using it.

Change tag using javascript [duplicate]

This question already has answers here:
Can I change an HTML element's type?
(9 answers)
Closed 4 years ago.
I want to know how can I change a tag with pure javascript like that
<span>some text</span>
I want to change it to that
<div>some text</div>
I have no idea how to do it.
You can't change the type of an element like that, instead you have to create a new element and move the contents into it. Example:
var e = document.getElementsByTagName('span')[0];
var d = document.createElement('div');
d.innerHTML = e.innerHTML;
e.parentNode.replaceChild(d, e);
Demo: http://jsfiddle.net/Guffa/bhnWR/
Just written a jQuery plugin for this.
(function( $ ) {
$.fn.replaceTag = function(newTag) {
var originalElement = this[0]
, originalTag = originalElement.tagName
, startRX = new RegExp('^<'+originalTag, 'i')
, endRX = new RegExp(originalTag+'>$', 'i')
, startSubst = '<'+newTag
, endSubst = newTag+'>'
, newHTML = originalElement.outerHTML
.replace(startRX, startSubst)
.replace(endRX, endSubst);
this.replaceWith(newHTML);
};
})(jQuery);
Usage:
$('div#toChange').replaceTag('span')
The biggest advantage of this method is that id preserves all the attributes of the original element.
If jquery is acceptable use replaceWith.
$('span').each(function() {
$(this).replaceWith($('<div>' + this.innerHTML + '</div>'));
});
Here is a JSFIDDLE working DEMO
If using jquery
Var spantxt = $('span').text();
$('body').append('<div>'+spantext+'</div');
Note this would only work if there was only one span, use an id selector otherwise
You can't do it.
What you want to do is to take content of your span,
then delete it and create new div and fill it with previous content.
Assumption: The span you want to replace is wrapped in a div with id "foo"
In pure javascript you could do something like:
var original_html = document.getElementById('foo').innerHTML;
original_html = original_html.replace("<span>", "<div>");
original_html = original_html.replace(new RegExp("</span>"+$), "</div">)
document.getElementById('foo').innerHTML=original_html;
If however you can not necessarily expect the span to be tightly wrapped by an element you can consistently get (by id or otherwise), the javascript becomes fairly complex. In either case, the real answer here is: use jQuery.

Getting elements using Javascript

I have a bunch of input elements that have a particular substring in their IDs. Using javascript, is there a way to get these elements as an array? I wouldn't know the full ID - only the substring.
Is this any simpler if I use JQuery?
How about a non-jQuery answer...hmmm!?
function getAndFilter(elems, filter) {
var length = elems.length,
ret = [];
while (length--) {
if(filter(elems[length])) {
ret[ret.length] = elems[length];
}
}
return ret;
}
getAndFilter(document.getElementsByTagName('input'), function(input) {
// Your custom logic/rule goes here:
return input.id.substr(0,5) === 'HELLO';
});
Quite easy with jQuery. Example:
$("li[id^='comment']")
Select all "li" where id starts with "comment".
EDIT
To get those into an array:
var myArray = new Array;
$("li[id^='comment']").each(function() {
var thisId = $(this).attr("id");
myArray.push(thisId);
});
its simpler if you use jquery, otherwise you will have to start from document body, get its children, parse their ids, select matching elements, and continue down the tree.
jquery is definitely a good way to go.
Check out the attribute filters at jquery.com
Selectors API runs.
document.querySelectorAll("input[id*='yoursubstring']")
Works in IE8+, WebKit (Google Chrome, Safari), seems will work in next Opera and FF.

Categories