javascript - get attribute value by text value - javascript

<a href='http://example.com'>Goes To Example.com</a>
I want to get the href value of this. This link will always be on the page
I will usually do something like: document.getElementsByTagName('a')[5]. However, the number of links are always changing so it isn't reliable at all. Is there a way I can get it by the text Goes To Example.com?

As you said in comment you can use jquery, use Contains like bellow
$('a:contains("Goes To Example.com")')
DEMO

Use the JQuery :contains() selector. You can then get the attribute "href", as follows:
$("a:contains(Goes To Example.com)").attr("href");
For example, the following snippet will popup an alert with http://example.com inside it:
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
<a href='http://example.com'>Goes To Example.com</a>
<script>
alert($("a:contains(Goes To Example.com)").attr("href"));
</script>
</body>
</html>

You could use xpath:
document.evaluate(
'/html/body//a[text()='Goes To Example.com']/#href',
document, null, XPathResult.ANY_TYPE, null);
You can iterate over the result (which is of type XPathResult) using iterateNext.
See xpath documentation for details: https://developer.mozilla.org/en-US/docs/Web/API/document.evaluate.

You can do document.getElementById and give the id to the a tag. To get the text you can use innerHTML function
Working Fiddle
HTML Markup
<a id="test" href='http://example.com'>Goes To Example.com</a>
JS:
document.getElementById("test").innerHTML
If you want it by href attribute only then you have to loop it over
var els = document.getElementsByTagName("a");
for (var i = 0, l = els.length; i < l; i++) {
var el = els[i];
if (el.href === 'http://www.example.com/') {
alert(el.innerHTML);
}
}

You can do it like this:
var links = document.getElementsByTagName('a');
var requiredId = "";
for(var i=0; i<links.length; i++){
if(links[i].innerHTML == "Goes To Example.com"){
requiredId = links[i].getAttribute('id');
}
}

Related

How can set the title of all the links in a page

I would like to make some javascript code that once run adds a title of each link that is the title of the page it leads to. Sorry, all I can figure out is...
<body onload="replace()">
<script>
function replace() {
document.getElementsByTagName("a").title=this.href;
}
</script>
hi
hi2
hi3
</body>
But nothing happens and I can't figure it out.
more simple, just place correctly your script:
<body>
hi
hi2
hi3
<!-- Script for everything, just placed before </body>-->
<script>
document.querySelectorAll('a').forEach(A=>{ A.title = A.href })
</script>
</body>
getElementsByTagName returns a collection of elements, you need to use loop for setting whatever to each link.
<body onload="replace()">
<script>
function replace() {
// find all links
var links = document.getElementsByTagName("a");
// loop the collection and set title to each one
for (var i = 0; i < links.length; i++) {
links[i].title = links[i].href;
}
}
</script>
hi
hi2
hi3
</body>
Afaik, there is no way to detect a page title from a different page in JS. If you know the titles in advance, you can create a mapping object and loop over your links like so:
var map = [['link','title'],['link','title']];
$('a').each(function() {
for(var i=0; i<map.length; i++) {
if(map[i][0] == $(this).attr('src'))
$(this).attr('title', map[i][1]);
}
});
That should set all your links with the appropriate page titles based on matching the src attributes of each link against the link in your mapping object
You can use window.location.href instead of this.href. Also, you probably need to run through each link in the tag list:
function start() {
var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
links[i].title = window.location.href;
}
}
window.load = start();
hi
hi2
hi3
Try this answer, I have tried to add comments so that you could understand what has happened:
<a class="link" href="about.html">About</a>
<a class="link" href="careers.html">Careers</a>
<a class="link" href="contact.html">Contact</a>
<script>
//create a true array
var links = Array.from(document.getElementsByTagName("a"));
window.addEventListener(
"load", //Trigger Load event of window object
()=> //return this function
{
//links is an array of a-tag objects
for (let i = 0; i < links.length; i++)
{
//for each a tag object
//set the attribute targeted below
links[i].setAttribute
(
//target the title attribute
"title",
//set it to the current href attribute value of the that a-tag object
links[i].getAttribute("href")
);
}
}
);
</script>

How to find and change part of html in IE6 by javascript

I have webpage and I need to make some changes in this page. I am using IE6 in compatibility mode:
The part of html I need to change seems like this:
<SPAN title="Klepnutím otevřete"
class=attachment url="/Activities/Attachment/download.aspx"
userId="{4618A8F6-8B8F-E611-940B-005056834715}"
merchantId="{74F4AC81-FB14-DC11-BF2E-00145ED73B3E}"
attachmentType="5"
attachmentId="{1828327C-74A6-E611-940B-005056834715}">
<IMG border=0
src="/_forms/attachments/16_generic.gif"
align=absMiddle> Account.xml
</SPAN>
I would like to change the url to something else by javascript.
Is there some way how to do it? I know, that there are some fuctions like getelementbyId, but I can not use it, as this element does not have the ID. Also it seems, that I can not use xpath, as it is not supported in IE6.
Thanks for all replies!
You said you're getting this: Object doesn't support property or method 'getElementsByClassName'
That means the document doesn't have that method on it. Here's a good polyfill for that method in older IEs:
function getElementsByClassName(node, classname) {
var a = [];
var re = new RegExp('(^| )'+classname+'( |$)');
var els = node.getElementsByTagName("*");
for(var i=0,j=els.length; i<j; i++)
if(re.test(els[i].className))a.push(els[i]);
return a;
}
Once that function is declared, you can use it. Just remember that it's not a method on the document like it would be in older browsers.
var spans = var tabs = getElementsByClassName(document.body,'span');
for(var i = 0; i < spans.length; i++) {
var title = spans[i].getAttribute('title');
if(title === "Klepnutím otevřete") {
spans[i].setAttribute('url', 'this/is/your/custom/url.aspx')
}
}
Here, I used the title attribute to try and find the right span. I have no idea if this title is unique to just this span element, so you might need to validate that and select it differently if needed.
Simply use getElementsByTagName
var spans = document.getElementsByTagName('span');
for (var i = 0; i < spans.length; i++) {
// find an element with a certain class
if (spans[i].getAttribute('class') == 'attachment') {
// set new value
spans[i].setAttribute('url', 'some other url');
}
}
<SPAN title="Klepnutím otevřete"
class="attachment"
url="/Activities/Attachment/download.aspx"
userId="{4618A8F6-8B8F-E611-940B-005056834715}"
merchantId="{74F4AC81-FB14-DC11-BF2E-00145ED73B3E}"
attachmentType="5"
attachmentId="{1828327C-74A6-E611-940B-005056834715}">
<IMG border=0
src="/_forms/attachments/16_generic.gif"
align="absMiddle"/> Account.xml
</SPAN>

Javascript - getAttribute not working with getElementsByTagName

I want to detect the first letter of the src in an img tag with JavaScript and display an alert if the first letter does not match 'l' :
HTML :
<!DOCTYPE html>
<html>
<body>
<script src="imgDetect.js"></script>
<img src="l.jpg" />
<img src="a.jpg" />
</body>
</html>
Javascript :
x = document.getElementsByTagName('img').getAttribute('src');
if (x.charAt(0)!=='l'){
window.alert("message")
}
The problem is that the getAttribute does not work with thegetElementsByTagName.
The alert will show if getElementsByTagName is replaced by getElementById, (for only detecting single elements),
I would like it work across all tags in getElementsByTagName
It is because getElementsByTagName returns a NodeList object, which is an array like object with reference to multiple elements.
So document.getElementsByTagName('img') does not have a method called getAttribute, calling that will result in error. Instead you need to iterate through the list and test each element
x = document.getElementsByTagName('img');
for (var i = 0; i < x.length; i++) {
if (x[i].getAttribute('src').charAt(0) !== 'l') {
window.alert("message")
}
}
Demo: Fiddle
Also in your script, you have included the script in the page header, which when is executed the body of the pages is not yet loaded so, document.getElementsByTagName('img') won't return any elements.
You can use the window's load method to execute your script or move the script to bottom of the page
Using onload
window.onload = function () {
//this part of the script will be executed after the document is loaded completely
var x = document.getElementsByTagName('img');
for (var i = 0; i < x.length; i++) {
if (x[i].getAttribute('src').charAt(0) !== 'l') {
window.alert("message")
}
}
}
Script at the bottom
<img src="l.jpg" />
<img src="a.jpg" />
<script src="imgDetect.js"></script>
getElementsByTagName returns an array. You need to grab the element from the list before further accessing its attributes. Below is the updated code:
var images = document.getElementsByTagName('img');
for(var i = 0; i < images.length; i++) {
if(images[i].getAttribute('src') !== 'l') window.alert("message");
}

Get Attributes Value for multiple class

Im a Javascript beginner. I want to get attribute value on multiple class elements. I tried with IDs, but it's not revelent since IDs are supposed to be unique.
My HTML looks like this :
<a href="#" class="Test" onclick="myJavascriptFunc()" data="FooBar_1">
<a href="#" class="Test" onclick="myJavascriptFunc()" data="FooBar_2">
<a href="#" class="Test" onclick="myJavascriptFunc()" data="FooBar_3">
Any help would be appreciated.
Thanks
First close your anchor Tags
Test1
Test2
Test3
then use this javascript function
function myJavascriptFunc(item)
{
alert(item.getAttribute("data"));
return false
}
and let me know if it works
Trying using this:
function test(){
var x = document.getElementsByClassName("myClass");
var i;
for (i = 0; i < x.length; i++) {
var val = x[i].innerHTML; //innerHTML returns the written text inside the element tag
alert(val);
alert(x[i].getAttribute("data")); //this will give you the data attribute
}
}
You can get any other attribute you like from that element just by replacing the innerHTML by that attribute's name
I'm too late as always, but I would use the HTML 5 dataset attribute:
<!DOCTYPE html>
<html>
<head>
<script>
function doSomething(classname,func,datakey)
{
var hrefs = document.getElementsByClassName(classname), // get all elements with the class
i = 0; // initialize the loop
for(;i < hrefs.length; i++) // iterate through all elements
{
func(hrefs[i].dataset[datakey]); // execute the passed function with the content of the dataset as first argument
}
}
function alertval(value) // example function to do something with it
{
alert(value);
}
window.onload = function ()
{
doSomething("Test",alertval,"something"); // just test it
}
</script>
</head>
<body>
Test1
Test2
Test3
</body>
</html>
You are probably wondering why you can't just reach the data attribute using the this keyword from myJavascriptFunc(). That's because you are using inline event registration, and the this keyword then refers to the window object. To get around this you must make sure the this keyword is actually written into the onclick property.
var elems = document.getElementsByClassName('test');
for (var i = 0, len = elems.length; i < len; i++) {
elems[i].onclick = myJavascriptFunc;
}
function myJavascriptFunc() {
alert(this.getAttribute('data'));
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
FooBar_One<br>
FooBar_Two<br>
FooBar_Three
</body>
</html>
A way to see the difference:
<element onclick="myJavascriptFunc()">. // this refers to the window object as the element does not get passed along.
<element onclick="alert(this.getAttribute('data'));">. // this refers to the element.

javascript unobtrusive

i have an html page, which is consist of many hyperlink like this inside body tag...
User Name
then i decide to use unobtrusive javascript ... then i'd like to change all the "a" tag to be...
<a id="354313" href=#>User Name</a>
when i click the second link above, i want that it'll call a function like the first link does,...
my question is how to get all the "a" element inside body tag then apply a function depend it's id...
With jQuery, something like this:
$('a').click(function() {
var id = this.getAttribute('id');
// Do something...
});
If you want it to work on all elements ever created, use this:
$('a').live('click', function() {
var id = this.getAttribute('id');
// Do something...
});
I hope this is what you are trying.
<script type='text/javascript'>
var alA = document.getElementsByTagName("a");
for(var aCounter=0;aCounter<alA.length;aCounter++) {
var singleA = alA[aCounter];
singleA.onclick = function () {
window.open = "http://www.example.com/?id="+singleA.id;
}
}
<script>
What you're after is this code:
<script type="text/javascript">
window.onload = function WindowLoad() {
var arrLinks = document.getElementsByTagName("a");
for (var i = 0; i < arrLinks.length; i++) {
var oLink = arrLinks[i];
var sCurHref = oLink.href;
if (sCurHref.indexOf("?id=") >= 0) {
var ID = sCurHref.split("?id=")[1];
if (ID.length > 0) {
oLink.id = ID;
oLink.href = "#";
oLink.onclick = function() {
document.location.href = sCurHref;
return false;
}
}
}
}
}
</script>
This will iterate all the links, changing the visible HREF to "#" and preserving their functionality, applying the proper ID. (Though you didn't say what's the use of that ID)
Feel free to mess around with the live test case: http://jsfiddle.net/yahavbr/uMbEY/
Something like:
<script language="javascript">
function myFunction(id)
{
alert(id);
}
</script>
<a id="354313" onclick="myFunction(this.id);" href="#">;User Name<;/a>
Not sure though Test it :)
I will rather say that add class to the links u want to handle this way
<a class="mylink" ... >User Name </a>
Now read the elements by class name. If you are using new browsers or any JS library like JQuery its great.
var links = document.getElementsByClassName("mylink") //Method in Mozilla Browser
Above are the links that you can process nicely without getting into trouble.
// Function that you want to call
function fake(id)
{
// Your content
}
// Get all "a" elements and put it in an Array
var links = window.document.getElementsByTagName("a");
for (var i=0; i<links.length; ++i)
{
fake(links[i].id);
}

Categories