I have a js object slider.controlNav, that contains DOM elements. I need to save in variable source of image, that contains in link with class 'flex-active'.
jQuery.each(slider.controlNav, function(i, val) {
var dom_object = slider.controlNav.get(i);
console.log(dom_object)
});
Top code returns:
<a href="#0" class="flex-active">
<img src="img/slider-portfolio/logos/__ico__Fason$Active.png">
</a>
<a href="#1>
<img src="img/slider-portfolio/logos/__ico__Web$Active.png">
</a>
<a href="#2" class="flex-active">
<img src="img/slider-portfolio/logos/__ico__New$Active.png">
</a>
My code:
jQuery.each(slider.controlNav, function(i, val) {
var dom_object = slider.controlNav.get(i).find('img').attr('src');
console.log(dom_object)
});
After that in console i have error:
Uncaught TypeError: slider.controlNav.get(...).find is not a function
get function gives you the underlying DOM object. You need to convert it to jQuery object.
Try $(slider.controlNav.get(i)).find('img').attr('src');
Please check with this code.
jQuery("slider.controlNav a").each(function() {
var dom_object = jQuery(this).find('img').attr('src');
console.log(dom_object)
});
You do want to use this or val, which refers to the current element in the iteration:
jQuery.each(slider.controlNav, function(i, val) {
var src = jQuery(this).eq(i).find('img').attr('src');
console.log( src )
});
Alternatively, just use plain JS as follows:
slider.controlNav.forEach(function(val) {
var src = val.querySelector( 'img' ).src;
console.log( src );
});
See this jsbin
var flexActiveControlNavs = slider.controlNav.find(".flex-active");
jQuery.each(flexActiveControlNavs, function(i, val) {
var dom_object = flexActiveControlNavs.eq(i).find('img').attr('src');
console.log(dom_object);
});
This will return only the image sources that are a child of elements with class "flex-active".
Related
I have a page which has an anchor element:
<a id="courses" href="/courses">Courses</a>
And I want to add or update some params to the href, for example:
Add a country params: <a id="courses" href="/courses?country=US">Courses</a>
Update the country params from US to UK: <a id="courses" href="/courses?country=UK">Courses</a>
What's the best way to do it via JavaScript or jQuery?
You can pass a function as the second parameter to the .attr() to modify the href attribute.
Try the following way:
// set
$("#courses").attr('href','/courses?country=US');
console.log($("#courses").attr('href'));
// update
$('#setParam').click(function(){
$("#courses").attr('href', function(_, el){
return el.replace(/(country=)[a-z]+/ig, '$1UK');
});
console.log($("#courses").attr('href'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="courses" href="/courses">Courses</a>
<button id="setParam" type="button">Set Param</button>
Wrrite a custom function to handle adding properties to the href attribute.
// function to change href attribute
function addPropertyToCourses(prop,value) {
var courses = document.getElementById('courses');
if (courses.href.indexOf("?") == -1) {
courses.href += "?";
} else {
courses.href += "&";
}
courses.href += prop + '=' + value;
}
(function() {
// add properties
addPropertyToCourses("country", "UK");
addPropertyToCourses("someProp", "someValue");
})();
<a id="courses" href="/courses">Courses</a>
Use jquery .attr( function ) to add/edit href attribute of element. In function check if attribute hasn't country parameter, add to it and if has edit it.
$("#courses").attr("href", function(i, href){
var index = href.indexOf("?");
return (index == -1 ? href : href.substring(0, index)) + "?country=US";
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="courses" href="/courses">Courses</a>
Here's an example in both JavaScript, and jQuery.
Vanilla JavaScript
function updateCountry (element, country) {
var url = element.getAttribute('href');
if (url.includes('country')) {
url = url.replace(/(\?country=)[A-Z]{2}/, `$1${country}`)
} else {
url = url.concat(`?country=${country}`)
};
element.setAttribute('href', url);
console.log(element.getAttribute('href'));
}
var element = document.getElementById('courses');
updateCountry(element, 'US'); // Add
updateCountry(element, 'UK'); // Update
<a id="courses" href="/courses">Courses</a>
jQuery
function updateCountry (element, country) {
var url = element.attr('href');
if (url.includes('country')) {
url = url.replace(/(\?country=)[A-Z]{2}/, `$1${country}`)
} else {
url = url.concat(`?country=${country}`)
};
element.attr('href', url);
console.log(element.attr('href'));
}
var element = $('#courses');
updateCountry(element, 'US'); // Add
updateCountry(element, 'UK'); // Update
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="courses" href="/courses">Courses</a>
I have an array where each element refers to a bunch of svgs in another js file. I'm trying to get it so that my alert message uses the same string I use in the array variable.
var illustArr = ['map', 'privacy', 'payment', 'rewards', 'passcode'];
var bmAnim = document.getElementById('illus-'+illustArr[i]);
bmAnim.addEventListener('click', function(){
alert('illus-'+illustArr[i]);
});
Any ideas how to achieve that?
You can do it using a for-loop. Also make sure that you check if element exists so that you wont get an error.
var illustArr = ['map', 'privacy', 'payment', 'rewards', 'passcode'];
for (var i = 0; i < illustArr.length; i++) {
bmAnim = document.getElementById('illus-' + illustArr[i]);
if (bmAnim) { //check if element exists
bmAnim.addEventListener('click', function() {
alert('illus' + this.id);
});
}
}
<div id="illus-map">MAP</div>
<p>
<div id="illus-privacy">PRIVACY</div>
<p>
<div id="illus-payment">PAYMENT</div>
<p>
<div id="illus-rewards">REWARDS</div>
<p>
<div id="illus-passcode">PASSCODE</div>
You need to iterate over the array and assign the click function with the corresponding key in scope.
var illustArr = ['map', 'privacy', 'payment', 'rewards', 'passcode'];
illustArr.forEach(function (key) {
var bmAnim = document.getElementById('illus-' + key);
bmAnim && bmAnim.addEventListener('click', function () {
alert('illus-' + key);
});
});
You should use the Array#forEach function to iterate over the elements in your array before you attach any listeners to the click event. Also, you can use this.id in the event handler to reference the string illus-* with the desired suffix rather than accessing illustArr again.
var illustArr = ['map', 'privacy', 'payment', 'rewards', 'passcode'];
illustArr.forEach(function (e) {
document.getElementById('illus-' + e).addEventListener('click', handler)
})
function handler () {
alert(this.id)
}
<ul>
<li id="illus-map">Map</li>
<li id="illus-privacy">Privacy</li>
<li id="illus-payment">Payment</li>
<li id="illus-rewards">Rewards</li>
<li id="illus-passcode">Passcode</li>
</ul>
in my js function I had following
success: function (result) {
$.each(result, function (i, item) {
$("#tab-" + item.myType).append(result);
})
}
Now I've change this function and instead I have following
success: function (result) {
$("#tab-how To Access to the first result collection element ").html(result);
}
}
I tried with
$("#tab-" + result[0].item.myType).html(result);
but it didn't help.
Question is: How to access to the first js element inside result collection object
Any thoughts ?
Using console.log(result) I'm getting html snippets which I display on partial view
div class="product clearfix">
<div class="l-new">
<a href="#">
#Model.MyType (rendered as My Type)
</a>
....
</div>
You can try:
result[0] // if you have numeric indices in your result collection
OR
var firstItem = null;
for(var x in result) { // if you have named properties
firstItem = result[x];
break;
}
I have this code:
<div class="col3">
<a id = "training-launch-button" href="javascript:void(0);" title=" My title here" class="button" onClick="Test();">Launch</a>
</div>
function Test() {
var new_window= window.open('','Ratting','width=550,height=170,0,status=0,resizable=1');
new_window.document.createElement("div");
document.getElementsByTagName('div')[0].innerHTML = '<ol><li>html data</li></ol>';
}
something is not right, I dont see the ordered list item?
I eventually want to build some HTML in the new window.
Use this Js
function Test() {
var newWindow= window.open('','Ratting','width=550,height=170,0,status=0,resizable=1');
var newContent = "<HTML><HEAD><TITLE>One Sub Window</TITLE></HEAD>";
newContent += "<BODY><div><ol><li>html data</li></ol></div>";
newContent += "</BODY></HTML>";
newWindow.document.write(newContent);
newWindow.document.close();
}
I think this is your problem; getElementsByName returns an array, not one element, so;
new_window.document.getElementsByTagName('div')[0].innerHTML = '<ol><li>html data</li></ol>';
NB: I have a '[0]' in there
I would try
new_window.document.getElementsByTagName('div')[0].innerHTML = ...
This should do it:
var new_window= window.open('','Ratting','width=550,height=170,0,status=0,resizable=1');
var div = new_window.document.createElement('div');
new_window.document.body.appendChild(div);
div.innerHTML = '<ol><li>html data</li></ol>';
You are actually not appending the new div to the new document's body, you'll have to use .appendChild() method for that, see this :
function Test() {
var new_window = window.open('','Ratting','width=550,height=170,0,status=0,resizable=1');
var div = new_window.document.createElement("div");
new_window.document.getElementsByTagName('body')[0].appendChild(div);
div.innerHTML = '<ol><li>html data</li></ol>';
}
see here - working example
For example I've got the simple code:
<ul class="list">
<li>Download file 01</li>
<li>Download file 02</li>
</ul>
and I wish to store in variables only the file names: file01.pdf and file02.pdf, how can I cut them?
Many thanks for the help.
Cheers.
use
lastIndexof and substring
Give anchor tag an id
var elem = document.getElementById ( "anch1" );
elem.href.substring (elem.href.lastIndexOf ( '/' ) + 1 );
Using jQuery
$(function() {
$("ul.list li a").each ( function() {
alert ( $(this).attr ( "href" ).substring ($(this).attr ( "href" ).lastIndexOf ( '/' ) + 1 ) )
});
});
Though you don't have them in this case, in general you would want to strip off the ?search and #hash parts before looking for the last slash to get the file's leafname.
This is very easy using the built-in properties of the link object like pathname instead of processing the complete href:
var a= document.getElementById('link1'); // or however you decide to reference it
var filename= a.pathname.split('/').pop(); // get last segment of path
var fileNames = new Array();
$('.list a').each(function(i, item){
fileNames.push(this.href.substring(this.href.lastIndexOf('/') + 1))
});
This will give you an array of all the filenames, then:
for(var x=0; x<fileNames.length; x++)
{
// Do something with fileNames[x]
}
var myFilename = [];
$("ul.list li a").each(function() {
var href = $(this).attr('href');
var idx = $(this).attr('href').lastIndexOf('/');
myFilename.push((idx >= 0) ? href.substring(idx+1) : href);
});
Here another way:
var arr = [];
$("ul.list li a").each (function(){
arr.push( (this.href.match(/\/[^\/]+$/)[0] || '').substr(1) );
});
var files = $('a[href]').map(function() {
return this.pathname.match(/[^\/]*$/)[0];
});
a[href] will exclude anchors without hrefs (such as named anchors), and pathname will remove query strings and fragments (?query=string and #fragment).
After this, files will contain an array of filenames: ['file01.pdf', 'file02.pdf'].