Ordering elements by number in JQuery - javascript

how could I arrange the following div's by the value in the attribute amount with jquery? Thanks.
<a href="#" id="id1" class="lTest" amount="12">
<div>abcd1</div>
<a/>
<a href="#" id="id2" class="lTest" amount="64">
<div>abcd2</div>
<a/>
<a href="#" id="id3" class="lTest" amount="32">
<div>abcd3</div>
<a/>
<a href="#" id="id4" class="lTest" amount="8">
<div>abcd4</div>
<a/>

This one should work.
<!doctype html>
<html>
<head>
<script src='jquery.js'></script>
<script>
$(document).ready(init);
function init() {
var parent = $('#someid');
var children = $('a', parent);
children.sort(function(a, b) {
return parseInt($(a).attr('amount')) - parseInt($(b).attr('amount'));
})
$.each(children, function(i, child) {
parent.append(child);
});
}
</script>
</head>
<body>
<div id="someid">
<div>abcd2</div>
<div>abcd4</div>
<div>abcd3</div>
<div>abcd1</div>
</div>
</body>
</html>
[Edit] Replaced by a SSCCE to prove it's working. I've changed x in abcdx to the expected ordering. You should end up with abcd1, abcd2, abcd3 and abcd4 in this order.

Try this:
var links = $('a.lTest').sort( function(a,b) { return $(a).attr('amount') - $(b).attr('amount'); } );
for ( var i = 1; i < links.length; i++ ) {
links.eq(i-1).insertBefore( links.eq(i) );
}

first, assume the tags are surrounded by a div (id ="testDiv")
Sorry, my initial way of doing this is wrong...
DO NOT DO THIS: BROKEN!!! (See edit below)
var testDiv = $('#testDiv');
var children = testDiv.children('.lTest');
children.each(function() {$(this).remove();});
var testArray = $.makeArray(children);
testArray.sort(function(a,b){
return parseInt($(a).attr('amount')) - parseInt($(b).attr('amount');
});
children.each(function() {testDiv.append(this);});
EDIT: THIS IS WORKING VERSION:
var testDiv = $('#testDiv');
var children = testDiv.children('.lTest').remove();
children = children.sort(function(a,b){
return parseInt($(a).attr('amount')) - parseInt($(b).attr('amount'));
});
testDiv.append(children);

Your first comment on Tinister's answer indicates that your test page doesn't know anything about JQuery. Make sure you are properly including JQuery in your tests and that the HTML is correctly constructed. Then you will probably find that one of the other answers works.
John

Related

How to add a href into a div with Javascript

I would like to add <a href='https://google.com'> after a <div>.
Here is what I've been trying:
http://jsfiddle.net/L29e4ftj/
Is there someone who could help me out please?
Thank you!
Is that how do you want this ?
<div id="autoComplete_list">
<div data-id="2" class="autoComplete_result">
<span class="autoComplete_highlighted">google</span>
</div>
</div>
<script>
var aUrl = document.createElement("a");
aUrl.setAttribute("href", "https://google.com");
aUrl.innerHTML = "<span class='autoComplete_highlighted'>Google</span>"
document.querySelector("#autoComplete_list").appendChild(aUrl);
</script>
Problem
The way you are selecting the div is slightly wrong.
You use getElementsByClassName() which returns a list of elements, not a single element, so you will get [div] instead of div.
Solution
You can either get the first element of that list:
document.getElementsByClassName("autoComplete_result")[0]
or use the simpler Document.querySelector:
document.querySelector(".autoComplete_result") (which returns only one element, not an array).
window.onload=function() {
// Notice the [0] which selects ONLY the first matched element
var mydiv = document.getElementsByClassName("autoComplete_result")[0];
var a = document.createElement('a');
a.setAttribute('href',"https://www.google.com");
a.innerText = "google link";
mydiv.appendChild(a);
}
Seems that the getElementsByClassName is not returning as expected, so the appendChild is not working. I tried using querySelector and is working fine. Take a look at the code snippet below:
var mydiv = document.querySelector('.autoComplete_result');
var a = document.createElement('a');
a.setAttribute('href',"https://www.google.com");
a.innerText = "google link";
mydiv.appendChild(a);
<body>
<div id="autoComplete_list">
<div data-id="2" class="autoComplete_result">
<span class="autoComplete_highlighted">goog</span>le
</div>
</div>
</body>

How to swap contents of header tag - HTML/Javascript

I have the following:
function changeFirst() {
let p = document.getElementById("firstElement")[0].innerhtml;
alert(p);
if (p = "<h1>This is the 1st element</h1>") {
document.getElementById("firstElement").innerHTML = "<h1>Changed first</h1>"
} else {
document.getElementById("firstElement").innerHTML = "<h1>Switched back first</h1>"
}
}
<div id="firstElement">
<h1>This is the 1st element</h1>
</div>
<button onclick="changeFirst()">Change first element</button>
I basically want the button to alternate the contents of the firstElement div. Why doesn't this work?
Thank you
document.getElementById returns ONE element
Also = is assignment, you want == or === for comparison
Could you possibly mean this:
function changeFirst() {
let h = document.querySelector("#firstElement h1");
h.textContent = h.textContent==="This is the 1st element" ? "Changed first" : "This is the 1st element"
}
<div id="firstElement">
<h1>This is the 1st element</h1>
</div>
<button type="button" onclick="changeFirst()">Change first element</button>
Here is exactly what you asked for. You were close.
1) when including javascript, you can just use script tags and it will work fine, when you use JSON or JQuery, that's when you have to use an include tag of a .js file. javascript code can be notated with script type = text/javascript.
2) when making a comparison in javascript: use three equal signs (===)
when making a non variable type-sensitive comparison: use two equal signs (==)
when setting a variable: use one equal sign (=)
https://www.geeksforgeeks.org/difference-between-and-operator-in-javascript/
3) When calling dynamic header, it is not an array, so you don't need [0], you are just comparing the innerhtml of the dynamic header div and it is only one header, arrays are for multiple things. Keep working on code, as you seem to have a good start, and made some minor syntax errors.
<!DOCTYPE html>
<html>
<body>
<button onclick="changeHeader()">Click me</button>
<div id="dynamicHeader"><h1>Hello World</h1></div>
<p>Clicking the button changes the header.</p>
<script>
function changeHeader() {
if (document.getElementById("dynamicHeader").innerHTML === "<h1>Hello World</h1>") {
document.getElementById("dynamicHeader").innerHTML = "<h1>Goodbye World</h1>";
} else {
document.getElementById("dynamicHeader").innerHTML = "<h1>Hello World</h1>"
}
}
</script>
</body>
</html>
Try like this. Here I introduced a flag and switched it to check content.
var changed = false;
function changeFirst() {
if (!changed) {
changed = true;
document.getElementById("firstElement").innerHTML = "<h1>Changed first</h1>";
} else {
changed = false;
document.getElementById("firstElement").innerHTML = "<h1>Switched back first</h1>";
}
}
<div id="firstElement">
<h1>This is the 1st element</h1>
</div>
<button onclick="changeFirst()">Change first element</button>

How to print array in order have same class name div

How to print array in order have same class name div. i try this code but it was print the same value of the last array. have any other way to do this
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function(e) {
var sss = '5#45#41#25#65';
var full = sss.split('#');
var mainid = full[0];
var full_sub = full[1].split('#');
var sub_count = full_sub.length;
alert(sub_count);
for(var i=0;i<sub_count;i++)
{
$(".block").attr(data-id,full_sub[i]);
$(".block").html(full_sub[i]);
}
});
</script>
<div class="block" data-id="" ></div>
<div class="block" data-id="" ></div>
<div class="block" data-id="" ></div>
<div class="block" data-id="" ></div>
Try
$(".block").each(function(index)
{
$(this).attr("data-id",full_sub[index]);
$(this).html(full_sub[index]);
});
In your code, each time you are assigning the html() to whole elements with the class .block. Here the html() is assigned to each tags with the same class name.
Also you forgot to put data-id in "". Otherwise it will take it as a variable, which causes the error..
Your current code overwrites all of the elements with the class of block in each loop iteration. Instead, create a parent element and append elements:
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function(e) {
var sss = '5#45#41#25#65';
var full = sss.split('#');
var mainid = full[0];
var full_sub = full[1].split('#');
var sub_count = full_sub.length;
alert(sub_count);
var parent = document.querySelector('#parent');
for(var i=0;i<sub_count;i++)
{
var div = document.createElement('div');
div['data-id'] = full_sub[i];
div.textContent = full_sub[i];
parent.appendChild(div);
}
});
</script>
<div id="parent"></div>
Working JSFiddle
If you do that way it will always print the same value of the last array.
You should use JQuery append function to append block div into a wrap div.
<script type="text/javascript" src="js/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function(e) {
var sss = '5#45#41#25#65';
var full = sss.split('#');
var mainid = full[0];
var full_sub = full[1].split('#');
var sub_count = full_sub.length;
alert(sub_count);
for(var i=0;i<sub_count;i++)
{
$("#wrapBlock").append('<div class="block" data-id="'+ full_sub[i] +'">'+ full_sub[i] +'</div>');
}
});
</script>
<div id="wrapBlock"></div>
That's my solution, hopefully it's helpful!
Try this.
HTML
<div class="block" ></div>
<div class="block" ></div>
<div class="block" ></div>
<div class="block" ></div>
Script
var sss = '5#45#41#25#65',
full = sss.split('#'),
full_sub = full[1].split('#');
$('.block').each(function(index){
$(this).attr('data-id', full_sub[index]);
$(this).html(index+1);
});
Fiddle Demo
The problem is that when you call $(".block").html(full_sub[i]);, you are setting it on all the divs with class .block; By doing the loop, you overwrite them each time and once you get out of the loop, they are set to the last value
Anoop's code works, an alternative is
var blocks = $(".block");
for(var i=0;i<sub_count;i++)
{
$(blocks[i]).attr('data-id',full_sub[i]);
$(blocks[i]).html(full_sub[i]);
}
The trick is that you can get at each of the items in jQuery's collection by using obj[intIndex] so that you're not dealing with all of them.
The each method is the jQuery way of doing it, it will iterate through each of the elements in the jQuery object, passing it the index, and this will point to the element being iterated
$(".block").each(function(index) {
$(this).attr("data-id",full_sub[index]);
$(this).html(full_sub[index]);
});

Javascript: How to call <li> element value

can anyone give me the javascipt code to extract following instances of sf_number from my HTML?
<ul class="multi_value_field" style="width: 99.5%;">
<li class="choice" choice_id="sf_number">sf_number<a class="close">×</a><input type="hidden" name="ticket[set_tags][]" value="sf_number" style="display: none;"></li>
<li class="search_field_item"><input type="text" autocomplete="off" tabindex="20"></li>
</ul>
Basically I want to replace all three instances of sf_number with a different
value from another field. This is the code I have made to try and extract sf_number but doesn't work so far:
var n2 = document.getElementsByClassName("multi_value_field").getElementsByClassName("choice");
Thanks in advance
UPDATE
How can I change my existing code by using your suggestions below?
<html>
<script type="text/javascript">
copy = function()
{
var n1 = document.getElementById("ticket_fields_20323656");
var n2 = document.getElementById("choice").getElementsByClassName("sf_number")[0] ;
n2.value = n1.value;
}
</script>
<input type="button" value="copy" onClick="copy();" />
</html>​​​​​
Update
This doesn't seem to work, is it correct?
<html>
<script type="text/javascript">
copy = function()
{
var fields = document.getElementsByClassName("multi_value_field")[0].getElementsByClassName("choice");
for (var i = 0; i < fields.length; i++)
fields[i].setAttribute("choice_id", "document.getElementById("ticket_fields_20323656").value");
fields[i].getElementsByTagName("input")[0].value = "document.getElementById("ticket_fields_20323656").value";
fields[i].firstChild.nodeValue = "document.getElementById("ticket_fields_20323656").value";
}
</script>
<input type="button" value="copy" onClick="copy();" />
</html>​​​​​
Try this code. Do you also want to replace the text?
<script>
var fields = document.getElementsByClassName("multi_value_field")[0].getElementsByClassName("choice");
for (var i = 0; i < fields.length; i++)
{
fields[i].setAttribute("choice_id", "something else");
fields[i].getElementsByTagName("input")[0].value = "something else";
fields[i].firstChild.nodeValue = "something else";
}
</script>
var n2 = document.getElementsByClassName("multi_value_field") returns a node List
So you need to use a for loop to iterate the list..
var n2 = document.getElementsByClassName("multi_value_field");
for(var i =0;i< n2.length;i++){
var $li = n2[i].getElementsByClassName("choice"); This is again a Node list.
for(var j = 0;j< $li.length ; j++){
$li[j] // This the li in question
}
}
UPDATE
var n1 = document.getElementById("ticket_fields_20323656");
var n2 = document.getElementById("choice").getElementsByClassName("sf_number");
// The above line again return's node List ....
n2.value = n1.value;
Replace that by this line with this if you feel it has a single class
var n2 = document.getElementById("choice").getElementsByClassName("sf_number")[0] ;
But the thing is I don't see the element with id="choice" in the HTML.
I'm not sure I understand your question.
There is no HTML attribute named "choice_id", and using non–standard attributes is not a good idea. If you want to identify a number of elements using the value 'sf_number', you should use a class instead, e.g.
<li class="choice sf_number">sf_number<a class="close">×</a>...</li>
Now you can get all elements with class of "sf_number" using getElementsByClassName, or querySelectorAll. You can add a shim for one or both of those to make life easier, then use:
var sfNumbers = document.querySelectorAll('.sf_number');
Then you can iterate over the collection per other answers.
An element can have multiple classes, the above will select only those with a class of 'sf_number'. If you want to select the text sf_number, you are much better off putting it in a span or similar element so you can reference it more directly. Relying on different browsers to insert text nodes consistently is not a good idea.

Add variable at the end of links (only without REL-attr)

I hope somebody can help me... I try to grab a parameter, which is saved in the head of a html-site, and add this parameter to all links on the site, which have no "rel='gallery'"-attribut. some links have allready other GET-parameters. It looks like this:
<head>
<script type="text/javascript">
var ParameterNew = "test";
</script>
</head>
[...]
Search: Google<br/>
Social Media: Facebook
<br/><br/>
<a rel="gallery" href="img/1.jpg">Gallery Link 1</a><br/>
<a rel="gallery" href="img/2.jpg">Gallery Link 2</a><br/>
So I try to append the ParameterNew behind all links, which have no rel-attribut.
At the end it has to looks lie this:
<head>
<script type="text/javascript">
var ParameterNew = "test";
</script>
</head>
[...]
Search: Google<br/>
Social Media: Facebook
<br/><br/>
<a rel="gallery" href="img/1.jpg">Gallery Link 1</a><br/>
<a rel="gallery" href="img/2.jpg">Gallery Link 2</a><br/>
I wrote this one. It only replace the innerHTML (such as an example):
var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
if (links[i].target !== "_blank")
links[i].innerHTML = 'test';
}
I only have problem to append the parameter... Maybe someone can help? thanx
This is a reasonably simple solution that takes into account your exact example conditions. That is, it assumes you have simple links so that all that needs to be done is check which connector to use in adding the parameter. If your links can contain parameters that are links, you'll need to do something more complex to figure out whether to use a ? or & to append the parameter.
var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
if (links[i].rel != 'gallery') {
var href = links[i].href,
connector = '?';
if (href && href.match(/\?/)) {
connector = '&';
}
links[i].href = href + connector + 'parameter=' + ParameterNew;
}
}

Categories