How to add attribute to child element <a> using JavaScript - javascript

I am facing issue in add attribute to child element in my scenario. Attribute is appending in parent instead of child tag . Please help me in JavaScript.
I have below code in html
<a href="#">
<div>dummy</div>
</a>
</div>
My Javascript is:
-----------------
document.getElementsByClassName('Master')[0].setAttribute('aria-label', 'demo');
Output is:
----------
<div class="Master" aria-label="demo">
<a href="#">
<div>dummy</div>
</a>
</div>
Expected output will be:
-------------------------
<div class="Master">
<a href="#" aria-label="demo">
<div>dummy</div>
</a>
</div>```

You need to select the specific anchor tag.
document.getElementsByClassName('Master')[0].getElementsByTagName('A')[0].setAttribute('aria-label', 'demo');
Suggest using a class directly in the anchor tag.

You can directly target the specific element (a) using Document.querySelector() that allows CSS like selector:
document.querySelector('.Master a').setAttribute('aria-label', 'demo');
console.log(document.querySelector('.Master a'));
<div class="Master" aria-label="demo">
<a href="#">
<div>dummy</div>
</a>
</div>
If you have multiple elements then use Document.querySelectorAll() and Array.prototype.forEach():
document.querySelectorAll('.Master a').forEach(function(el){
el.setAttribute('aria-label', 'demo');
});

Related

How can I click an anchor tag inside a list item?

I am trying to click the anchor tag inside the list item with raw js. How can I do it?
Code:
<li class="next">
<a href="#" class="btn btn-link">
<img src="/images/arrow-right.png" alt="newer">
</a>
</li>
You can try this:
document.getElementsByClassName('btn-link')[0].click();
Or you can give the <a> tag an id and do this:
document.getElementById('myId').click();
There are multiple ways to do this, but simply you can create a javascript function in a <script> tag at the bottom of the html page, and then tell the <a> anchor which function to call using the onclick attribute
<ul>
<li class="next">
<a href="#" class="btn btn-link" onclick="doClick(this)">
<img src="/images/arrow-right.png" alt="newer">
</a>
</li>
</ul>
<script>
function doClick(elem) {
console.log('clicked!', elem);
}
</script>

Change image with only jquery or javascript

I am trying to change an image from an old to new using jquery or javascript only. It is the second picture out of three total that has a common parent element and is not separated by any specific parameters.
I believe I need to use a DOM navigation of some sort to get to the exact picture in the common class but haven't had any luck.
As I mentioned the 'make' class is shared between all three images as is 'make-image'. I need to simply swap the image for another updated version, facebook1.jpg.
<li class="make ">
<a href="#">
<img class="make-image" src="facebook.jpg">
<div class="make-info">
<img class="make-logo" src="facebook.jpg">
<div class="clearall"></div>
</div>
</a>
</li>
It should simply swap the existing image for another.
You can query for the image tags inside the list-item and iterate with each over the returned array. Inside that loop you can check if the src of that image-element is what you are looking for and replace it.
$('li.make img').each(function(index){
if ($(this).attr('src') == 'facebook.jpg') {
$(this).attr('src', 'facebook1.jpg');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li class="make">
<a href="#">
<img class="make-image" src="facebook.jpg">
<div class="make-info">
<img class="make-logo" src="facebook.jpg">
<div class="clearall"></div>
</div>
</a>
</li>

How to get the title of anchor tag which is inside a list and having class as selected

I have an unstructured list(ul) inside div tags and I am trying to get the title of an anchor tag, which is inside an li that has class="selected".
<div class="mainmenu">
<div class="mainmenulinks">
<ul>
<li class="selected">
<a class="topmenu-navigation-links" id="topMenuItem0" href="" title="Private">
<span class="span-link-Private">Private</span>
</a>
</li>
<li>
<a class="topmenu-navigation-links" id="topMenuItem1" href="" title="Business">
<span class="span-link-Business">Business</span>
</a>
</li>
<li>
<a class="topmenu-navigation-links" id="topMenuItem2" href="" title="Broker">
<span class="span-link-Broker">Broker</span>
</a>
</li>
</ul>
</div>
</div>
In this case, I should be getting Private as its li has class="selected".
[Updated] Working Fiddle https://jsfiddle.net/prashantkumar_999/rd9zttyn/9/
You can use:
$("li.selected>a").attr("title")
If you need to be more specific, you can add before the li, eg:
$(".mainmenu .mainmenulinks li.selected a").attr("title")
Your fiddle doesn't work as you've
not included jquery
not included "." for some classes (but have for others)
with hasClass, it needs to be in quotes without ".", eg .hasClass("selected")
tried to use this outside of a relevant context
Prop vs Attr
Summary of Preferred Usage
The .prop() method should be used for boolean attributes/properties and for properties which do not exist in html (such as window.location). All other attributes (ones you can see in the html) can and should continue to be manipulated with the .attr() method.
while prop does work and is an easy fall-back incase you're not sure which to use, it should be attr for title.
Try this
$('li.selected').find('a').attr('title');
Updated Fiddle https://jsfiddle.net/rd9zttyn/3/ which is working fine

How to get href url if href contains in multiple div tag using jquery

I am new to jquery can i get href url if href attribute contains in anchor tag in div tag
<div id="testing">
<a onclick="window.location='http://linkedin.com'>linked</a>
<div id="my_div">
<a onclick="window.location='http://google.com'>google</a>
facebook
<a onclick="window.location='http://gmail.com'>gmail</a>
</div>
</div>
You can try like this
alert($('#my_div>a:nth-child(2)')[0].href);

Adding a new element HERE where the code is, not after another element

Made some BBcode for phpBB to allow users to post flickr pics with certain tags.
Each photo div in the thread needs to be unique, and the images load when the thread is loaded.
When it comes to the unique DIV, I'm stuck for a way to insert the uniquely named element into the DOM at the point the BBcode is inserted, THEN load the pics. And it appears I can't use PHP in BBcode, nor the templating tags - if I could easily make a unique photo element from the post ID and the flickr tag I'd be laughing. Oh, and I can't touch the template. It's all got to be within BBcode.
So, here's how I make a unique ID:
var flickrUser = "{URL}".split("/")[4];
var tag = "{URL}".split("/")[6];
var photoDIV = flickrUser + "-" + "tag";
Or...there's an element called with a unique post ID just above I could possibly use:
<div id="p61789" class="post bg2">
I tried
var postnumber=$(this).closest('div[class^="post"]').attr('id');
but it always seemed to return the FIRST matching div on the page, not the NEAREST to the point of the BBcode. This element is two "divs" below
<div class = "content">
and below the user posting area there is:
<div id="sig61789" class="signature">
So where I'm completely stuck is navigating to prev() or closest() or parent() or indeed anywhere from the point where I am without having a $(this) link to reference.
So shouldn't something like:
$(this).prev('content').html('<ul class="thumbs" id=photoDIV></ul>');
or even
$(this).html('<ul class="thumbs" id=photoDIV></ul>');
work? Everytime I think I understand jquery it all goes hazy again...
EDIT: More detail added for Pointy:
<div id="p63167" class="post bg2 online">
<div class="inner">
<span class="corners-top">
<span></span>
</span>
<div class="postbody">
<ul class="profile-icons">
<li class="edit-icon">
<a href="posting.php" title="Edit post">
<span>Edit post</span>
</a>
</li>
<li class="delete-icon">
<a href="posting.php" title="Delete post">
<span>Delete post</span>
</a>
</li>
<li class="report-icon">
<a href="report.php" title="Report this post">
<span>Report this post</span>
</a>
</li>
<li class="info-icon">
<a href="mcp.php" title="Information">
<span>Information</span>
</a>
</li>
<li class="quote-icon">
<a href="posting.php" title="Reply with quote">
<span>Reply with quote</span>
</a>
</li>
</ul>
<h3 class="first">
Re: Testing new bbcode - ignore
</h3>
<p class="author">
<a href="viewtopic.php">
<img src="" alt="Post" title="Post" />
</a>by
<strong>
xxx
</strong>ยป 13 Jun 2011 14:33</p>
<div class="content">
<script>var
APIkey="xxx";head.js("/forum/jflickrfeed/jflickrfeed.min.js","http://jquery-lazy.googlecode.com/svn-history/r14/trunk/jquery.lazy.source.js",function(){var
flickrUser="http://www.flickr.com/photos/xxx/tags/7thjanuary2010/".split("/")[4];var
tag="http://www.flickr.com/photos/xxx/tags/7thjanuary2010/".split("/")[6];var
photoDIV=flickrUser+"-"+"tag";$(this).html('
<ul class="thumbs" id="photoDIV">
</ul>');$.getJSON("http://www.flickr.com/services/rest/?jsoncallback=?",{method:"flickr.urls.lookupUser",url:"http://www.flickr.com/photos/xxx/tags/7thjanuary2010/",format:"json",api_key:APIkey},function(data){$('#cbox').jflickrfeed({limit:30,qstrings:{id:data.user.id,tags:tag},itemTemplate:'
<li>'+'
<a rel="colorbox" href="{{image}}" title="{{title}}">'+'
<img src="{{image_m}}" alt="{{title}}" />'+'</a>'+'</li>'},function(data){$('#cbox
a').colorbox();});});$.lazy([{src:'/forum/jflickrfeed/colorbox/colorbox/jquery.colorbox-min.js',name:'colorbox',dependencies:{css:['/forum/jflickrfeed/jflickrfeed.css','/forum/jflickrfeed/colorbox/example1/colorbox.css']}}]);});</script>
<ul id="cbox" class="thumbs"></ul>
</div>
<div id="sig63167" class="signature"></div>
</div>
</div>
</div>
the problem is you're assuming that the this context when you're executing within the script block is the script block itself, which is incorrect. If there is no context explicitly given, then your context is the window DOM element. Is there any reason you can't move this code to the page level, and initialize all the posts at page load?
$(function() {
$('.post').each(function(i,item) {
console.log(this); //Post DOM element.
//execute your flick retrieval code here.
});
}
Have you tried Javascript's DOM functions to add it?
http://www.javascriptkit.com/javatutors/dom2.shtml
For example, to insert right after the current script, with id "script1":
document.getElementById("script1").parentNode.appendChild( newelement );
You can add raw html too, just set innerHTML of the new element.

Categories

Resources