I am trying to overwrite an old link that is written into some code via a CMS, therefore I cannot access the base code easily.
I am trying to add a script that will overwrite the current link with a new one.
Here is my code:
script:
function linkChange() {
var links = document.getElementById("titlecontent");
links.getElementsByTagName("a").href = "http://www.cnn.com/";
}
or
function linkChange() {
document.getElementById("titlecontent").getElementsByTagName("a").href = "http://www.cnn.com/";
}
html:
<ul id="titlecontent"><li>link</li></ul>
The main issue is I cannot go in and add an id or class to the <a> tag, so I need to target it starting with the <ul> which has the id "titlecontent".
This works :
document.getElementById("titlecontent").getElementsByTagName("a")[0].href = "http://www.cnn.com/";
<ul id="titlecontent"><li>link</li></ul>
The problem was that you needed to select a specific element in getElementsByTagName, because it returns a list of elements, not just one.
Related
I have a navigation which is listed dynamically with PHP.
<nav id='navs'>
#foreach($element as $val)
<a data-prop={{$val->id}}>$val->name</a>
#endforeach
</nav>
The html :
The highlighted the tags are listed dynamically
I have a JS script, when we click on the navbar element then we add .selected class to the tag.
When the page is loaded the first tag has .selected class.
I need a JS code to find the data-prop attribute value for the elements with .selected class.
I tried:
var d= $("#navs .selected").attr('data-prop');
but the d variable is undefined. Any suggestion? I also tried the .find() method.
For the given example one could to the following:
first get an array of all related elements
d = $("#navs > a");
And then iterate and get your desired attributes:
for (index = 0; index < d.length; ++index) {
console.log(d[index].getAttribute("id"));
}
... the given example prints the ID attribute instead your custom attribute (data-prop)
I figured out what the problem was. I have a script which is adding the class name .selected to the tags, the problem is that it executed AFTER my script, where I wanted to find the element with the .selected class.
So my code is working:
var d= $("#navs .selected").attr('data-prop');
I need a little bit of help with my shopify store. I'm trying to change the class of a button in order to style it from the default class "btn" to "askAQButton". However, the code for the buttons are not in the markup at all and so I can only assume they're generated by JS by the shopify plugin itself.
I figured it should be simple and I should be able to just target the element by "id" with jquery and change class. However, the button doesn't have an ID and neither does the href...
My next thought was okay, target the parent div by id, then target the class of the button and href and change it that way (to avoid targeting duplicate classes).
I just can't seem to get it working.
Here is all the markup I'm given to implement this onto my store page:
Obviously a lot of it is irrelevant (probably all of it besides the parent div) however, when I load my page up after implementing this code it auto-generates this right under the second input:
<div class="wk-ask-order">
<button class="wk-ask-a-question-order btn" style="display: inline-block;">Raise a Query
</button>
View Your Queries
</div>
Can anyone help me with targeting it and changing the class names please.
I'm not sure if I get the question right, but there might be a problem with the button having not yet been injected into the DOM at the time when your script is targeting it.
Try waiting for the DOMContentLoaded event before executing your code:
document.addEventListener('DOMContentLoaded', () => {
const askAQBtn = document.querySelectorAll('.wk-ask-a-question-order')[0]; //there's probably a better selector
askAQBtn.classList.replace('btn', 'askAQButton');
});
If that doesn't work, have a look at MutationObserver to wait for the specific element to exist. I found a snippet for this on Github:
https://gist.github.com/jwilson8767/db379026efcbd932f64382db4b02853e
This was my answer it's a bit lo-fi but I hope it gives you something to work from. I followed your idea regarding the parent div id.
let parent = document.getElementById('wk-askme');
let child_nodes = parent.childNodes;
for (let i = 0; i < child_nodes.length; i++) {
let item = child_nodes[i];
if ($(item).attr('class') == "wk-ask-a-question-order btn") {
$(item).attr('class', 'wk-ask-a-question-order askAQButton');
}
}
I wrote a masking jquery that is suppose to add dynamic elements the an existing input element.
var link = $('<a title="show" role="link" href="#" class="masker-value">show</a>');
wrapper: function() {
container = $(container)
.attr('ispartial', this.options.partial)
.attr('readyonly', this.options.readyOnly);
$(this.element).wrap(container);
if (!this.options.hideToggle)
$(this.element).after(link);
}
If I have a single input on a page, the code above works fine, but if I have multiple input, the link is only added to the last input.
Demo
Add the following line to the wrapper function:
link = $('<a title="show" role="link" href="#" class="masker-value">show</a>');
You defined link globally outside the wrapper function so its always refering to the same object, which gets moved in the DOM.
Example: https://jsfiddle.net/nxvdm5hr/5/
Further explanation:
When you use $('<a/>'), jQuery creates an input DOM element.
When you .after() that element, it detaches from the previous position.
You could also modify the var link to just HTML code, which will also fix your problem.
My navigation menu on header looks like this:
<ul id="nav">
<li id="home">
<a class="mainmenu" href="#">Link1</a>
</li>
<li>
<a class="mainmenu" href="#">Link2</a>
</li>
</ul>
and the same markup is used for the footer section and it's not working.
I have also a file called jscript.js which contains all the javascript for the website,
and I found this variable:
var navTarget = "ul#nav li a" //menu link to target
Also, if I remove for example the markup in the header sections the footer will work.
I've tried also to use .nav instead of #nav and I have the same problem.
The navigation menu is controlled by javascript, I don't post the code here because it's huge, for better understanding of how the navigation menu works look here
I've found this in the javascript:
//SET MENU ITEM IDs
$(navTarget).each(function(i){
i++
this.id = this.id +"_" +i ;
});
//MENU CLICK FUNCTION
$(navTarget).click(function() {
//ensure link isnt clickable when active
if ($(this).hasClass('active')) return false;
//get id of clicked item
activeNavItem = $(this).attr('id');
//call the page switch function
switchContent();
});
//CONTENT SWTICH FUNCTION
var switchContent = function (){
//set previous and next link & page ids
var PrevLink = $(navTarget+'.active')
$(PrevLink).removeClass('active');
var PrevId = $(PrevLink).attr('id');
//alert(PrevId)
var NextLink = $('#'+activeNavItem).addClass('active');
var NextId = activeNavItem
//alert(NextId);
From the looks of it, the JS code is using some CSS selector (like jquery's $ or dojo's dojo.query) that pulls in the DOM element target based on the value of navTarget, and then does something with it: turns it into a menu.
But its only doing it once.
You need to look at the JS and see where navTarget is used. Then it should be fairly easy to make it do the menu creation on all the results of $(navTarget) instead of just the first hit.
Also, you should only have on instance of an ID in your dom.
You can change this to a class instead:
var navTarget = "ul.nav li a"
And in the markup:
<div class='nav'>
But you will still have to look at the JS and make sure it functions against a set of targets returned by the CSS selector. That code is probably expecting just a single result and using just it: results[0].
You can only have one element of a given id on the page. So based on your description, it sounds like you have 2.
I don't know exactly how this script works, but you can try using classes instead.
<ul class="nav">
var navTarget = "ul.nav li a";
You would have to change your HTML and the JS navTarget selector string.
But there is also a good chance that your script may not support creating multiple menus at all. And if thats the case, you may need to fix that script or find a better one.
If the code for the footer really is identical to the header, that's the problem. An id should only be used for a single element in a page, and jQuery's selectors will only return the first. Meaning code like "ul#nav li a" only works on the header.
Easiest solution is to change the id's to classes, e.g.:
<ul class="nav">
... and change your jQuery to match that, e.g.:
var navTarget = "ul.nav li a";
Update: And (ignoring that this may end up turning into three duplicate posts), that fix is probably not enough at all, since other parts of the script may only work with a single menu.
Is there any way to add classes or alter objects that is dynamically added to the body?
I am adding a range of objects to the body by javascript.
Fot instance Im adding some links that is dynamically generated and added to the body. When they are loaded I need to elect the first of the divs and add a new class to it.
I can't seem to find any way to do this... Update the DOM or how should I go around this? There must be a way to alter dynamically added objects.
Any clues?
Thanks for any help!
if you added them dynamically, then you can just use the objects you already have. Otherwise you'll need to find them with sizzle.
//create the elements
var $link1 = $('<a>click me</a>').attr('href','page1.html');
var $link2 = $('<a>click me</a>').attr('href','page2.html');
//append the elements
$('#some-links').append($link1).append($link2);
//use the element we created
$link1.addClass('my-class');
//find the second link element using sizzle
$('#some-links>a').eq(1).addClass('my-other-class');
demo: http://jsfiddle.net/PtebM/2/
Well of course you caN:
var a = $('<a>');
a.html('new link').appendTo('#menu');
a.addClass('border');
or
var a = $('<a>');
a.html('new link').appendTo('#menu');
$('#menu a').addClass('border');
fiddle http://jsfiddle.net/4NPqH/
Why not just add a class name to your generated elements?.
I.e.:
$('span').html('Hello world').addClass("fancyText").appendTo('body');