Get innerHTML of class elements - javascript

I am using the function getElementsByClassName to get an array of elements and then use .innerHTML but it returns me the following text:
HTML
<input class="form-control input-block" value="Algorithms to live by" type="text">
JAVASCRIPT
function save_book(event){
var id = event.target.id;
var book = document.getElementsByClassName(id);
console.log(book[0].innerHTML)
}
and I only want the value. When I display the array of elements I find the .innerHTML returns the value but I get this.
Thanks!

With the given function, you need to grab the captured elements child element (the input), not its innerHTML, and with that you then get is value using e.g. book[0].firstChild.value
function save_book(event){
var id = event.target.id;
var book = document.getElementsByClassName(id);
console.log(book[0].firstChild.value)
}

Use dot notation to extract the value attribute:
function save_book(event){
var id = event.target.id;
var book = document.getElementsByClassName(id)[0];
var bookValue = book.value;
console.log(bookValue)
}

You should try this -
var dom = document.getElementsByClassName("input-block")[0].value;
console.log(dom); //Algorithms to live by

Related

Get the tagName element inside class

I want to get the element of a inside class and change it.
My HTML is:
<div class="alignleft">
« Older Entries
</div>
I want to change Older Entries to Previous.
My JavaScript code is:
var oldentries = document.querySelector('.alignleft');
var ainside = document.getElementsByTagName('a');
oldentries.ainside.innerHTML = "Previous";
but that gives me undefined.
Once you use Document.querySelector() to get the elements with class '.alignleft' you can also do oldentries.querySelector('a'); to get the 'a' element within oldentries and then change the element.innerHTML:
var oldentries = document.querySelector('.alignleft'),
ainside = oldentries.querySelector('a');
ainside.innerHTML = 'Previous';
<div class="alignleft">
« Older Entries
</div>
You need to update the textContent property of the <a> element.
Working Example:
var linkElement = document.querySelector('.alignleft a');
linkElement.textContent = 'Previous';
<div class="alignleft">
<a>Older Entries</a>
</div>
You can look for your element using a signle call to querySelector by using a more precise selector : Directly use .alignLeft a instead of doing it twice.
This code works :
var entries = document.querySelector('.alignLeft a');
entries.innerHTML = "Previous"
Your code would render out to something like
document.querySelector('.alignleft').document.getElementsByTagName('a').innerHTML = "Previous";
Also, getElementsByTagName('a') would render an Array not an object which you can apply .innerHTML to.
var ainside = document.querySelector('.alignlef a'); // Select first occurance of a inside the first occurance of .alignleft in the document
ainside.innerHTML = "Previous";
document.getElementsByTagName returns a HTML Collection. So you need to iterate over it (in your case it would be the first entry).
var oldentries = document.querySelector('.alignleft');
var ainside = document.getElementsByTagName('a');
for(i=0;i<ainside.length;i++) {
ainside[i].innerHTML = "Previous";
}

jQuery selecting attribute value of multiple elements with name attribute

I have a form that has multiple input, select, textarea elements. With jQuery, How can I get the name attribute values of each element? I have tried the following but its not working:
var names = $('[name]');
names.each(function(){
console.log(names.attr('name'));
})
You need to use this within the each() to refer to the element within the current iteration. Your current code is attempting to get the name of a set of elements which is logically incorrect. Try this:
var names = $('[name]');
names.each(function(){
console.log($(this).attr('name'));
})
You are still using names within your each function. Try this:
var names = $('[name]');
names.each(function(index, name){
console.log($(name).attr('name'));
})
This should loop around all the required elements and output the name and value to the console.
$('input,select,textarea').each(function() {
var thisname = $(this).attr('name');
var thisval = $(this).val();
console.log('name = ' + thisname);
console.log('value = ' + thisval);
});
You can try this way too.
var $name = $("[name]");
$name.get().map(function(elem,index){
console.log($(elem).attr("name"));
});
Add a class to all the elements you wish to get the names of.
Then you get all the elements from that class and iterate them to get their names.
formElements = $('.form-element');
for(key in formElements) {
name = formElements[key].attr('name');
// do what you wish with the element's name
}
P.S. You may need to wrap formElements[key] in $(), have not tested it.
// Selects elements that have the 'name' attribute, with any value.
var htmlElements = $("[name]");
$.each(htmlElements, function(index, htmlElement){
// this function is called for each html element wich has attribute 'name'
var $element = $(htmlElement);
// Get name attribute for input, select, textarea only
if ($element.is("input") ||
$element.is("select") ||
$element.is("textarea")) {
console.log($element.attr("name"));
}
});
Give your input ID then call attr() method
$("#id").attr("name");

Using JQuery's .attr() When Selector Returns Multiple elements

I am trying to pull 2 pieces of data from each of several fields. All the fields have been given the same "name" so as to allow them to be referenced easily.
<input type="text" name="common_name" data-X='ABC'>
The first piece of data I am pulling is their values, which does seem to be working. My issue is when I try to use attr(). It just stops dead in the water at that point.
var length = $('[name=common_name]').size();
for(var i=0; i < length; i++){
var value = parseInt($('[name=common_name]').get(i).value); //doesn't kill the script
var dataX = $('[name=common_name]').get(i).attr('data-X'); //Script is killed here
}
Since I'm not having issues with using attr() in general when the selector is selecting the element based on an id, I would think the issue has to do with the fact that in this case multiple elements are being returned by jQuery. What I am confused by is that I thought that get(#) is supposed to grab a specific one…in which case I don't see what the problem would be. (After all, using get(#) DOES work when I use val()).
So…why doesn't attr() work here?
.get() returns a dom element reference which does not have the .attr() method, so you can use the .eq() method which will return a jQuery object
var length = $('[name=common_name]').size();
for (var i = 0; i < length; i++) {
var value = parseInt($('[name=common_name]').eq(i).val()); //doesn't kill the script
var dataX = $('[name=common_name]').eq(i).attr('data-X'); //Script is killed here
}
The correct way to iterate over an jQuery object collection is to use the .each() method where the callback will be invoked for each element in the jQuery collection
$('[name=common_name]').each(function () {
var $this = $(this);
var value = parseInt($this.val()); //or this.value
var dataX = $this.attr('data-X'); //or $this.data('X')
})
Suppose the html is like this
<input type="text" name="common_name" data-X='ABC'>
<input type="text" name="common_name" data-X='DEF'>
<input type="text" name="common_name" data-X='GHI'>
Now the script part
$('input[name="common_name"]').each(function() {
var el = $(this);
text_val = el.val();
data = el.attr('data-X');
console.log(text_val);
console.log(data);
});
attr is a jquery fn, should call by jquery object
use like this
$('[name=common_name]').attr('data-X')
so try
dataX = $($('[name=common_name]').get(i)).attr('data-X');

Javascript innerHTML updating issue

I have the following JavaScript line:
<div id="box" name="1" margin="4px" padding="4px" onclick="memory(1)"></div>
With the associated memory() function being:
function memory(a) {
var tmpDar = a-1;
var m = document.getElementsByName(tmpDar);
m.innerHTML = arrA[tmpDar];
}
However, when I try executing the code, the HTML doesn't alter... Can somebody please help me?
document.getElementsByName() returns a NodeList and not a single element!
So in order to set the innerHTML of your div, you have to reference an entry inside that array, e.g., like this:
function memory(a) {
var tmpDar = a-1;
var m = document.getElementsByName(tmpDar);
m[0].innerHTML = arrA[tmpDar];
}
In your code you set the innerHTML property for the NodeList object, which has no (visual) effect in the document.
In general it would be better to use id instead of name. Then you could use document.getElementById() in a way like this:
function memory(a) {
var tmpDar = a-1;
var m = document.getElementById(tmpDar);
m.innerHTML = arrA[tmpDar];
}
document.getElementsByName returns an array. So if the element that you want is unique with this name, you should replace your code by :
function memory(a) {
var tmpDar = a-1;
var m = document.getElementsByName(tmpDar);
m[0].innerHTML = arrA[tmpDar]; // Here I have added index 0
}
your trying to find all elements with a name of 0 as far as I can tell. And there is no 0 name.
Also what the other two said, it returns an array you need to call an index on that array.

use variable part of ID with js

I have a list of 8 divs: #video1, #video2, ... with each the same javascript actions to run when clicked, but with other id's (for #video1: show #image1, #preview1, ...).
Instead of writing 8 times the same code but with other id's, can I do this more efficient? Is it possible to take the sixth caracter (the number) from each #videoX as a variable when clicked, and use
this in the code?
Inside your event handler, you can extract the number, e.g. with a regular expression [MDN]:
var id = element.id.match(/\d+$/)[0];
and then use it to create the IDs of the other elements:
var image_id = "image" + id,
preview_id = "preview" + id;
Another option would be to assign data- attributes to the elements and use them to store the numerical part of the ID.
Use a class name instead. This way it's independent of the IDs completely.
<div class="videoClick" id="...">...</div>
JS:
$('.videoClick').click(function() {
...
})
yes you can:
$("div[id*='video']").click(function() {
var numid = $(this).attr("id").replace("video", "");
alert(numid);
//...use your numid value
});
Check attribute contains selector.
Try this
var ids = [#video1, #video2, #video3, #video4, #video5, #video6, #video7, #video8];
$(ids.join(",")).click(function(){
var imageId = this.id.replace("video", "image");
var previewId = this.id.replace("video", "preview");
$("#"+imageId).show();
$("#"+previewId).show();
});

Categories

Resources