Jquery each through <a> gives me href only - javascript

I have a simple menu
<div class="nav-container desktop">
One
Twp
</div>
I am looping through this with jQuery each and then creating <li> tags with the complete <a.../a>.
$.each( $('.nav-container>a'), function(i, item){
var menupunkt = '<li>' + item + '</li>'
console.log(i, menupunkt);
});
Examples: http://codepen.io/anon/pen/bwbgap, https://jsfiddle.net/86g44ssp/
In my console I see only the following
<li>http://xyz.ccom/_index.php?page=_sub_papa&main=tw</li>"
Why don't I get the whole a? Because when I just print "item" I get the whole <a.../a>

item or this represent a DOM element. You're casting it to string when you treat it as as string. You can use item.outerHTML - the string you're looking for - in place of item.
$.each( $('.nav-container>a'), function(i, item){
var menupunkt = '<li>' + item.outerHTML + '</li>'
console.log(i, menupunkt);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="nav-container desktop">
One
Twp
</div>
NOTE
Not sure if there's an advantage to it but I would prefer:
$('.nav-container>a').each(function(i, item){
var menupunkt = '<li>' + item.outerHTML + '</li>'
console.log(i, menupunkt);
});

I have updated your fiddle, you just need to change
var menupunkt = '<li>' + item + '</li>'
to
var menupunkt = '<li>' + item.outerHTML + '</li>'
And there is no need to add extra wrapping or stuff, just get the HTML from outerHTML and you're done !

$.each( $('.nav-container>a'), function(i, item){
var menupunkt = '<li>' + $(item).text() + '</li>'
console.log(i, menupunkt);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="nav-container desktop">
One
Twp
</div>

I believe you want to access the outerHTML. I've included code from another SO answer:
jQuery, get html of a whole element
https://jsfiddle.net/86g44ssp/1/
The change I've made is here:
jQuery.fn.outerHTML = function() {
return jQuery('<div />').append(this.eq(0).clone()).html();
};
... other code here ...
var menupunkt = '<li>' + $(item).outerHTML() + '</li>'

This is caused by type conversion. When you do '<li>' + item + '</li>' the JavaScript runtime will try to convert item to a string. This is done "under the hood" by calling toString() method on the item, e.g. item.toString(). You can do forced type conversion by doing it explicit:
console.log(i, item.toString());

$( ".nav-container a" ).wrap( "<li></li>" );
This is the fastest way to wrap .nav-container a inside list element.
While looping $.each('.nav-container a', function(i,v) {}); each <a> are like object NOT at TEXT
if you want target specific elements use:
$.each('.nav-container a', function(i,v) {
var fullObject = $(this).html(),
link = $(this).attr('href'),
text = $(this).text();
});

Related

sorting through an array to place code in the proper divs through jQuery

Currently making a website to index and play movies stored on my hard drive that I've recently pulled off dvds just as a little side project. I have a 'master movie list' JSON file with all the data I need for each movie including the name, video source, video poster source, and genre which I would like to allow the use of placing a movie in multiple different genres.
Currently the problem I'm having is while I'm parsing through the genre list generated its not placing the html in the correct ID that id like it to on the webpage.
For example:
"genre":"comedy,recent,scifi"
I went about it how I thought I should, through getJSON and setting an output variable to which I get the genre value, split to make it an array, and get the element by going through each of them in a loop. Its not placing it in the right place though. The example above would be placed in comedy, recent, scifi, horror, and a few others for some reason and I have absolutely no reason why.
$.getJSON('/webresource/data/movies.json', function(data) {
console.log(data);
var output = '';
var ele = $('');
$.each(data, function(key, val) {
output += '<div class="video_box lazy-background" video-src="' +
val.video_src + '" video-poster-src="' +
val.video_poster_src + '">' +
'<h5>' + val.name + '</h5>' +
'</div> ';
var genres = val.genre;
var genresarray = genres.split(',');
for (i = 0; i < genresarray.length; i++) {
var genreelement = $('#' + genresarray[i]);
genreelement.html(output);
}
});
});
[ {
"name": "a star is born", "video_src":"/files/movies/A%20Star%20Is%20Born/astarisborn.mp4", "video_poster_src":"https://images-na.ssl-images-amazon.com/images/I/51R-TU6VaTL.jpg", "genre":"recently,romance,drama"
}
] // this is an example of the json
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="genre_box">
<h3>RECENTLY ADDED</h3>
<div class="scroll_box" id="recently"></div>
</div>
<div class="genre_box">
<h3>ACTION</h3>
<div class="scroll_box" id="action"></div>
</div>
<div class="genre_box">
<h3>COMEDY</h3>
<div class="scroll_box" id="comedy"></div>
</div>
Your output variable is being appended to and kept on every iteration of your $.each loop. What you want is to append to the end of $("#action"), $("#comedy"), etc. You should do something along these lines:
$.getJSON('/webresource/data/movies.json', function(data) {
console.log(data);
$.each(data, function(key, val) {
var output = '<div class="video_box lazy-background" video-src="' +
val.video_src + '" video-poster-src="' +
val.video_poster_src + '">' +
'<h5>' + val.name + '</h5>' +
'</div> ';
var genres = val.genre;
var genresarray = genres.split(',');
for (var i = 0; i < genresarray.length; i++) {
var genreelement = $('#' + genresarray[i]);
genreelement.append(output);
}
});
});

Replacing <img> tags with links to their content jquery

As the title says, I am having some issues converting images to links using jquery. My code right now is:
var all_img = $(".message .content").find("img");
$.each(all_img, function (index, value) {
var src = value.src;
value.replaceWith($("<a href='" + src +"'>Image " + index+1 + "</a>"));
});
Which results in the images being replaced with [object Object]. I have also tried:
$.each(all_img, function (index, value) {
var src = value.src;
value.replaceWith("<a href='" + src +"'>Image " + index+1 + "</a>");
});
Which results in the html I am trying to insert going in as plain unclickable text. Am I misunderstanding how .replaceWith() works?
You couldn't call the jQuery .replaceWith() method on value, you need to use a jQuery object, to target the current img in every iteration you need to use $(this) like :
all_img.each(function (index, value) {
var src = value.src;
$(this).replaceWith("<a href='" + src +"'>Image " + index+1 + "</a>");
});
I think it is better to create a new element and remove/hide the img:
$('.turnInAnchor').click(function(e){
$('img').each(function(index, el) {
$('body')
.append("<a href='"+el.src+"' target='_blank'>Image "+index+"</a>");
el.remove();
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="turnInAnchor">Turn in anchor</button>
<img src="https://upload.wikimedia.org/wikipedia/it/7/75/Twin_Peaks_Episodio_Pilota_Laura_Palmer.png" />

Optimize way to append element in html using jquery

What is the optimize way to append this element to my specific DIV Class using JQUERY. This will generate dynamic elements. I use .AppendTo then display dynamically the element inside <div class='parent-list-workorder'>.
Here's my code so far but it doesn't work:
$(document).ready(function(){
var ListOfWorkOrders = [];
$("#button").click(function(){
//var _WOID = $('.list-workorder-id').text();
var _WOID = $('#txtWOID').val();
//alert(_WOID);
$.ajax({
url:'getWorkOrders.php',
type:'POST',
data:{id:_WOID},
dataType:'json',
success:function(output){
for (var key in output) {
if (output.hasOwnProperty(key)) {
$("<div class='child-list-workorder'>
<div class='list-workorder'>
<div class='list-workorder-header'>
<h3 class='list-workorder-id'>" + output[key] + "</h3>
</div>
<p>" + Sample + ":" + key + "</p>
</div>
</div>").appendTo("<div class='parent-list-workorder'>");
//alert(output[key]);
}
}
console.log(output);
}
});
});
});
Am I missing something?
Your problem is in the code below:
.appendTo("<div class='parent-list-workorder'>");
The parameter of appendTo() should also be a valid selector.
you can try this instead:
.appendTo("div.parent-list-workorder");
granting that div.parent-list-workorder already exists.
You have two problems. First, you need to use a selector as an argument to .appendTo(), not an HTML string. Second, you need to remove or escape the newlines in the HTML string.
$("<div class='child-list-workorder'>\
<div class='list-workorder'>\
<div class='list-workorder-header'>\
<h3 class='list-workorder-id'>" + output[key] + "</h3>\
</div>\
<p>" + Sample + ":" + key + "</p>\
</div>\
</div>").appendTo("div.parent-list-workorder");

how to refresh the list in jquery javascript

Hi i m having one page with one textbox named search and one search button. When i'm searching anything for the first time it's showing me the right data but when i'm searching some other things for the next time then the elements which was listed before are also appended below of that new list. Suppose i'm searching state name by k it will give me right list of karnataka, kerala. But if i start to search again by g, it will show me in output as goa,gujrat,karnataka kerala. i tried using refresh option but it still not working. This is my js code
$.each(response.state, function (i, state) {
$('#statelist').append(
'<li>' +
'<a href="#">'
+
+'<b>'+ '<font color="green">'+'<h3>'+ state.Name +'</h3>'+'</font>' +'</b>'+
'</a>' +
'</li>'
);
});
$('li img').width(100);
$('.ui-li-icon li').click(function() {
var index = $(this).index();
text = $(this).text();
// alert('Index is: ' + index + ' and text is ' + text);
});
$("#statelist").listview("refresh");
and this is html
You are using .append() function. It appends whatever you append to the end of the list.
Check this link:
http://api.jquery.com/append/
Try using innerHTML property of the DOM model.
You could add
If(!('#statelist').html() == ""){
$(this).remove();
//execute rest of code that appends state list
}
Then do an else statement and execute your append code without removing()
UPDATE: a better option is to do this-
$.each(response.state, function (i, state) {
$('#statelist').html(
'<li>' +
'<a href="#">'
+
+'<b>'+ '<font color="green">'+'<h3>'+ state.Name +'</h3>'+'</font>' +'</b>'+
'</a>' +
'</li>'
);
});
$('li img').width(100);
$('.ui-li-icon li').click(function() {
var index = $(this).index();
text = $(this).text();
// alert('Index is: ' + index + ' and text is ' + text);
});

Jquery append() isn't working

I have this <ul>
<ul id="select_opts" class="bullet-list" style="margin-left:15px;"></ul>
This javascript code which is meant to go throug a JSON object and add the options
to the UL:
$.each(q.opts, function(i,o)
{
var str='';
str+="<li id='li_" + i + "'><input type='text' id='opt_" + i + "' value='" + o.option + "'>";
str+=" (<a href='javascript:delOpt(" + i + ");'>Delete</a>) </li>";
$("#select_opts").append(str);
});
If I do console.log() I can see that the looping is working. If I do:
console.log($("#select_opts").html());
It shows the HTML being updated as expected. However in the browser window, it shows the
UL as empty!
What am I doing wrong?
$("select_opts").append(str);
should be
$("#select_opts").append(str);
you're referring to object by id so you missed #
$.each(q.opts, function(i,o)
{
var str='';
str+="<li id='li_" + i + "'><input type='text' id='opt_" + i + "' value='" + o.option + "'>";
str+=" (<a href='javascript:delOpt(" + i + ");'>Delete</a>) </li>";
$("#select_opts").append(str);
// ^
}
I can't really see what's wrong, but try this instead, just to see if it works...
$(str).appendTo("#select_opts");
Both should work.
Is this a typo?:
$("select_opts").append(str);
Did you mean?:
$("#select_opts").append(str);
UPDATED:
Try this:
$.each(q.opts, function(i, o) {
var li = $('<li>').attr('id', 'li_' + i);
var in = $('<input>').attr('type', 'text').attr('id', 'opt_' + i).val(o.option);
var aa = $('<a>').attr('href', 'javascript:delOpt(' + i + ');').text('Delete');
li.append(in).append(aa)
$("#select_opts").append(li);
});
The tag Input should be closed - if don't, when using not valid html in append() on Internet Explorer, the div is not put into DOM tree, so you cannot access it with jQuery later.
I'd imagine input needs to be properly self-closed.
I found the bug, another part of the code was emptying the <ul> when i clicked a certain button.

Categories

Resources