Please consider this HTML:
<a class="title" threedots="Product Name 1"></a>
<a class="title" threedots="Product Name 2"></a>
<a class="title" threedots="Product Name 3"></a>
I want to change it to this:
<a class="title" threedots="Product Name 1">Product Name 1</a>
<a class="title" threedots="Product Name 2">Product Name 2</a>
<a class="title" threedots="Product Name 3">Product Name 3</a>
using JavaScript or jQuery. I can change the first occurrence only with this:
var fullName = document.getElementsByClassName("title")[0].getAttribute("threedots");
document.getElementsByClassName("title")[0].innerHTML = fullName;
But I need help writing a script that can change all of the occurrences. I have researched foreach and HTMLcollection, but I don't understand them. Can someone point me in the right direction for writing a script that will find each <a class="title"> and grab the value for its threedots attribute and inject it in?
You could simply select all the elements by their [threedots] attribute and class name, then iterate over them using a simple for loop:
var elements = document.querySelectorAll('.title[threedots]');
for (var i = 0; i < elements.length; i++) {
elements[i].textContent = elements[i].getAttribute('threedots');
}
Or using .forEach():
var elements = document.querySelectorAll('.title[threedots]');
Array.prototype.forEach.call(elements, function (el) {
el.textContent = el.getAttribute('threedots');
});
As a side note, since you're only changing text, you can use the .textContent property rather than .innerHTML. In addition, threedots isn't a valid attribute. Consider using a data-* attribute such as data-threedots:
<a class="title" data-threedots="Product Name 1"></a>
<a class="title" data-threedots="Product Name 2"></a>
<a class="title" data-threedots="Product Name 3"></a>
Then you can access the the property .dataset.threedots:
var elements = document.querySelectorAll('.title[data-threedots]');
for (var i = 0; i < elements.length; i++) {
elements[i].textContent = elements[i].dataset.threedots;
}
Since you mentioned jQuery, you could also use the following:
$('.title[data-threedots]').text(function () {
return $(this).attr('data-threedots');
});
So instead of only using the first index of document.getElementsByClassName("title") we can iterate it.
var titles = document.getElementsByClassName("title");
for(var i = 0; i < titles.length; i++) {
var title = titles[i];
title.innerHTML = title.getAttribute("threedots");
}
a {
display: block;
}
<a class="title" threedots="Product Name 1"></a>
<a class="title" threedots="Product Name 2"></a>
<a class="title" threedots="Product Name 3"></a>
You select all anchor elements using jQuery and set it.
$('a').each(function(){
$(this).html($(this).attr('threedots'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="title" threedots="Product Name 1"></a>
<a class="title" threedots="Product Name 2"></a>
<a class="title" threedots="Product Name 3"></a>
Related
I am trying to click some buttons in a page which has this html code
<div class="a">
<span>
<a class="b" role="button">test</a>
</span>
</div>
So what i've tried is to take ONLY the div's class a
var buttons = document.getElementsByClassName('a').getElementsByClassName('b');
for(var i = 0; i <= buttons.length; i++)
buttons[i].click();
Is there anyway to get the button with class name b but Only the one that is inside the div with class name a ??
P.S. i have also tried and this
var buttons = document.getElementsByClassName('a').getElementsByTagName('span').getElementsByClassName('b');
for(var i = 0; i <= buttons.length; i++)
buttons[i].click();
But i get an empty array [ ] as a response when I console.log(buttons)
You can use querySelector to overcome the issue.
document.querySelectorAll("div.a a.b");
You can use jquery and do
var buttons = $('.a > .b');
Here's an XPath solution:
let res = document.evaluate('//*[#class="a"]//*[#class="b"]',document,null,XPathResult.ANY_TYPE,null);
res.iterateNext().click();
<div class="a">
<span>
<a class="b" role="button" onclick="console.log('clicked!')">test</a>
</span>
</div>
Unfortunately Internet Explorer still doesn't support the XPath API.
Since only one div will be assigned the class='a', you can either supply an ID instead, or, you can do this :
var spans = document.getElementsByClassName('a')[0].getElementsByTagName('span');
// [0] indicates the first element with the class='a'
for(var i = 0; i < spans.length; i++) {
spans[i].getElementsByClassName('b')[0].click();
}
<div class="a">
<span>
<a class="b" role="button" href="javascript:void(0)" onclick="console.log(this.innerHTML+' was clicked !')">test 1</a>
</span>
<span>
<a class="b" role="button" href="javascript:void(0)" onclick="console.log(this.innerHTML+' was clicked !')">test 2</a>
</span>
<span>
<a class="b" role="button" href="javascript:void(0)" onclick="console.log(this.innerHTML+' was clicked !')">test 3</a>
</span>
</div>
This works perfectly, here it is : https://jsfiddle.net/nd8m7mms/4/
I have html controls of two sets with different ids in my page, when I click a tag I want to call DoSomething method.
<div>
<a href="javascript:void(0);" onclick="DoSomething();">
<span id="spnValue" >Value1</span>
</div>
<div>
<a href="javascript:void(0);" onclick="DoSomething();">
<span id="spnValue1">Value2</span>
</div>
function DoSomething() {
var htmlVal = "";
skuList = $("span[id*='spnValue']").html();
}
But whichever one I click it gives the Value1 in htmlVal. How can I distinguish and retrieve the value of method called
You can pass clicked element object to method:
<a href="javascript:void(0);" onclick="DoSomething(this);">
<span id="spnValue1">Value2</span>
</div>
and then use it for traversing to child span element:
function DoSomething(obj) {
var htmlVal = "";
skuList = $(obj).find('span').html();
}
Working Demo
<div>
<a href="javascript:void(0);" onclick="DoSomething(this);">
<span id="spnValue1">Value2</span>
</div>
function DoSomething(obj) {
var htmlVal = "";
skuList = $(obj).parent().find('span').html();
}
You can pass the current element in the function using that you can locate the span element which is a children on the a tag
<div>
<a href="javascript:void(0);" onclick="DoSomething(this);">
<span id="spnValue" >Value1</span>
</a>
</div>
<div>
<a href="javascript:void(0);" onclick="DoSomething(this);">
<span id="spnValue1">Value2</span>
</a>
</div>
function DoSomething(node) {
var htmlVal = "";
skuList = $(node).find('span').html();//for children
//skuList = $(node).next('span').html();//for siblings
}
I have an HTML string that holds sets of list items. I want to extract the image url and the correspondent href value from <li></li> sets and use these values as variables for later.
<img src="./season/123434mango.jpg" width="180" height="148"
alt="mango season" class="png">
example of <li></li> set:
<li>
<img src="./season/123434mango.jpg" width="180" height="148"
alt="mango season" class="png">
<div class="thumbnail_label">ok</div>
<div class="details">
<div class="title">
<a href=
"/mango/"> mango</a>
<span class="season">2</span>
</div>
<ul class="subject">
<li>read</li>
</ul>
<ul class="sub-info">
<li class="location">Europe</li>
<li class="price">2</li>
</ul>
</div>
</li>
If you're using jQuery then you can do:
var data = [];
$($.parseHTML(siteContents)).each(function() {
$(this).find("img").each(function() {
var parent = $(this).parent();
data.push({
SRC: $(this).attr("src"),
HREF: parent.find("a").attr("href"),
LOCATION: parent.find(".location").text(),
PRICE: parent.find(".price").text(),
SUBJECT: parent.find(".subject li").text()
});
});
});
You can then use the array "data" that contains objects. Each of which has a "SRC", and "HREF" attribute associated with it.
See this jsFiddle for an example of it in use.
UPDATED BASED ON COMMENTS
See this jsFiddle example. The key change is instead of looking for "li" you pass it $.parseHTML(siteContents);
If you are using jQuery this will do the trick and will be organized. I updated with a parseHTML.
//Instead of using each, always think about use for, will be faster.
var imagesSourceAndLinkHref = {sources: [], hrefs: []},
i = 0,
code = $.parseHTML('<div><li><img src="./season/123434mango.jpg" width="180" height="148" alt="mango season" class="png " /></li></div>'),
list = $(code).find('li'),
images = list.find('img'),
links = list.find('a');
for(i; i < images.length; i++) {
imagesSourceAndLinkHref.sources.push(images.attr('src'));
}
for(i = 0; i < links.length; i++) {
imagesSourceAndLinkHref.hrefs.push(links.attr('href'));
}
console.log(imagesSourceAndLinkHref);
See this jsFiddle
Cheers!
I have a number of <li> items, which call the same onmouseover javascript function.
The function needs to extract some data from the element that calls it, to fill some name and tel variables. This data is typed in capitals in the html code below.
Any idea on how to do this is really appreciated.
My HTML:
<li id="item1" onmouseover= "onmouseoveragent(this)" >
<a href="some link">
<span class="hideme">name</span>
</a>
<p class="hideme"> NAME TO BE PASSED TO JS
<strong class="tel">NUMBER TO BE PASSED TO JS</strong>
</p>
</li>
MY javascript:
<script language="javascript" type="text/javascript">
function onmouseoveragent(e) {
var name = e.?????;
var tel = e.?????;
};
</script>
yes you do something like this
JAVASCRIPT:
var elements = document.getElementsByClassName('data-item');
var mouseoverHandler = function() {
var name = this.getElementsByClassName('name')[0].textContent,
tel = this.getElementsByClassName('tel')[0].textContent;
alert('Name - ' + name + "\nTel - " + tel);
}
for( var i = 0; i < elements.length; i++ ) {
var current = elements[i];
current.addEventListener('mouseover', mouseoverHandler);
}
HTML MARKUP:
<li id="item1" class="data-item">
<a href="some link">
<span class="hideme">name</span>
</a>
<p class="hideme">
<span class="name">John Smith</span>
<strong class="tel">555-666-777</strong>
</p>
</li>
<li id="item1" class="data-item">
<a href="some link">
<span class="hideme">name</span>
</a>
<p class="hideme">
<span class="name">Caprica Smith</span>
<strong class="tel">545-334-641</strong>
</p>
</li>
MDN - document.getElementsByClassName();
MDN - element.textContent
It won't be e.something because e is referring to the event that just happened, that has nothing to do the other elements in the DOM
Demo
Well, there is an easier way to do it, just traverse the childNodes of your current hovered element and parse the results. Here is a working JSFiddle of the snippet below(yes, it works with all the LIs matching that structure):
function onmouseoveragent(e) {
var children = this.childNodes,
name = null,
tel = null;
for (var i = 0; i < children.length; i++) {
var child = children[i];
if (child.tagName === 'P') {
name = child.firstChild.nodeValue; // the first node is the text node
tel = child.childNodes[1].firstChild.nodeValue; // the strong's text node
break; // let's stop the iteration, we've got what we needed and the loop has no reason to go on
}
}
console.log(name, tel); // "NAME TO BE PASSED TO JS " "NUMBER TO BE PASSED TO JS"
}
The only difference in HTML is that you need to pass your handler this way:
<li id="item1" onmouseover="onmouseoveragent.call(this, event)">
So this inside the handler will refer to the element and not to the global object.
I suggest you two thing one change the structure of you li tag i.e; make the tag as shown
<li id="item1" class="someClass" >
<a href="some link">
<span class="hideme">name</span>
</a>
<p class="hideme">NAME TO BE PASSED TO JS </p>
<strong class="tel">NUMBER TO BE PASSED TO JS</strong>
</li>
remove strong from p because when you try to fetch p(data to be passed the strong tag will come along with it so better change it)
and also try jquery it will give you more flexibility and ease of use(what i feel)
$(".someClass").mouseover(function(e){
var name = $(e.target).find("p:first").html()
var tel = $(e.target).find("strong:first").html()
})
try this
function onmouseoveragent(e) {
var text = e.getElementsByClassName('hideme')[1].textContent;
var name = text.split("\n")[0]; var num = text.split("\n")[1]; alert(name); alert(num); }
I'm pretty new to javascript. I have this sample table. I want to be able to get the "http://www.msn.com" but haven't been able to do so. How should I do this?
thanx in advance
j
<body>
<div id="tableContainer">
<table width="100%">
<thead>
<tr>
<th width="16%" > </th >
<th width="62%"> Otras acciones</th >
<th class="sort" width="2%"> Código certificado</th>
<th class="sort" > Descripción</th>
</tr>
</thead>
<tbody>
<tr>
<td class="iconos" >
<span class="sigAccion">
<a href="#" class="sigIcnHref" title="Duplicar" />
<span class=" btnDuplicar">
</span></a>
<a href="http://www.msn.com" class="sigIcnHref" title="Modificar" />
<span class=" btnModificar">
</span></a>
</span> </td>
<td class="AccionRegistro">
<ul>
<li>
<a href="#" >Docència </a></li>
<li>
<a href="#" >Matrícula(S) </a></li>
<li>
<a href="#" >Plans(1) </a></li>
<li>
<a href="#" >Professors(1) </a></li>
<li>
<a href="#" >Horaris(9) </a></li>
<li>
<a href="#" >HorarisProfessors(1) </a></li>
</ul></td>
<td > <sup>2</sup>CAMD</td>
<td> Cert. Alumno Matriculado Ext.</td>
</tr>
</tbody>
</table>
</div>
</body>
straight javascript is pretty easy.
grab a reference to a known element above the a element higher up the tree
get a list of a elements under the known element
match the href property to the value you know
var anchor = null;
var container;
var items;
container = document.getElementById('tableContainer');
items = container.getElementsByTagName('a');
for (var j = 0; j < items.length; j++) {
if (items[j].href === 'http://www.msn.com') {
anchor = items[j];
break;
}
}
it would be better if you could directly reference the table element and then get a list of a elements from there, but if that's the only table in tableContainer it's fine.
for checking the href property for a known value, i usually go with a case-insensitive regex but this should be fine for your case.
Using a framework like jQuery it's pretty simple:
var href = $('#tableContainer .iconos a[title=Modificar]').attr('href');
Using plain Javascript it's more complicated if you can't simply add an id to the element to make it easier to locate it. You can for example look through all links in the page:
var href;
var links = document.links;
for (var i = 0; i < links.length; i++) {
if (links[i].title == 'Modificar') href = links[i].href;
}
you can also do this by using jQuery
$('#tableContainer a').each(function() {
if (this.href == 'http://www.msn.com'){
// Do something like $(this).hide();
}
else {
// Do somthing like $(this).show();
}
});
here is an example of JSFiddle
If the structure is always like this, a code for Prototype would look like this:
var allLinks = $$('#tableConatiner tbody tr td span a');
var msnLInk = allLinks[1].href;
You can also use jQuery with a similar selector or even pure JS which will need some additional selections. But using an id attribute (e.g. "msnLink") you can get it using a direct selection:
var msnLink = $('msnLink').href;
I can you extend the code with an ID?
EDIT: If the title or class is unique and always the same you can also use one of the following lines:
var msnLink = $$('a[class="sigIcnHref"]').first().href;
var msnLink = $$('a[title="Modificar"]').first().href;
Can you give us some more information about the structure and what you want to do with the element after selecting it?