How to get the Previous Sibling name - javascript

I need to get the name of the previous sibling . to keep it simple i have some sample code
<html>
<head>
<script type="text/javascript">
function myFunction()
{
var itm=document.getElementById("item2");
alert(itm.previousSibling.name);
}
</script>
</head>
<body>
<p name='pn'>paragraph</p>
<button id='item2' onclick="myFunction()">Try it</button>
</body>
</html>
Edit:
<table id="sort">
<tr name="nodrag nodrop">
<td colspan=3><strong><a style="cursor:pointer;" class="toggle">Group 1</a></strong> </td>
<td style="text-align: right;"><a class="button3" href="#" ><span> Edit </span></a> <a class="button3" href="#" ><span> Delete </span></a></td>
</tr>
<tr id="1" class="tr_group"'>
<td style="width:10px;" class="dragHandle"> </td>
<td>Umair Iqbal</td>
<td><span style="font-size: 12px; color: #999; line-height: 100%;">A Student at TUM</span></td>
<td style="text-align: right;"><a class="button3" href="#" ><span> Edit </span></a> <a class="button3" href="#" ><span> Delete </span></a></td>
</tr>
The Ist row is the previous sibling of the second row. I want the name of the 1st row and all my ids will be dynamic
thanks

Using jQuery it would be:
$('#item2').prev().attr("name")​​​​​​​​​​;​
With regular javascript you would need to use the following function (to ensure whitespace nodes are ignored)
getPreviousSiblingName(document.getElementById("item2"))
function getpreviousSiblingName(element) {
var p = element;
do p = p.previousSibling;
while (p && p.nodeType != 1);
return p.attributes["name"].value;
}

That's because more likely your previousSibling will be a text node and not an element node. You need previousElementSibling (where supported) or a loop that will get the previousElement until the nodeType will be 1 (Node.ELEMENT_NODE).
In addition, name is not applying to p element (see https://developer.mozilla.org/en/DOM/Element.name) it could be better if you use a custom attribute (like an HTML5 data-* attribute, in your case data-name maybe) and therefore use dataset to get the attribute's value, or a generic getAttribute.
Of course library like jQuery can help to abstract all those things, the explanation is related to just vanilla JavaScript.

Related

Get value from span inside list with id

I have the following code where I want to retrieve the value of the span element inside an anchor tag, inside a list element with an id.
parseInt($('#top_cart_button.span').text(), 10);
<li id="top_cart_button">
<a href="default.asp?cmd=showCart" rel="nofollow">
<span>€ 55,00</span>
</a>
</li>
How can I do it?
Thank you
#top_cart_button.span will try to find the first element with class span that is a child of the element with id top_cart_button. You want to find the element with the tag span and not the class. To do so, remove the .. Then, to remove the extra character, you can extract only the numbers from the input using the extractDigits function below.
Here's a working example:
let InputText = $('#top_cart_button span').text();
let InputDigitsOnly = extractDigits(InputText);
function extractDigits(input) {
return input.match(/\d+/g).map(Number);
}
console.log(parseInt(InputDigitsOnly, 10));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li id="top_cart_button">
<a href="default.asp?cmd=showCart" rel="nofollow">
<span>€ 55,00</span>
</a>
</li>
EDIT:
var prezzo = parseInt($('.mainPriceAmount').text().split(",")[0], 10);
var InputText = $('#top_cart_button span').text().split(",")[0];
var InputDigitsOnly = extractDigits(InputText);
function extractDigits(input) {
return input.match(/\d+/g).map(Number);
}
var carrello = parseInt(InputDigitsOnly, 10);
var somma = prezzo + carrello;
var customLink = '<img alt="Hello" src="https://ps.w.org/click-fraud-check/assets/icon-128x128.png?rev=2160665"/>';
if (prezzo >= 199 || somma >= 199) {
$('#customHTML').show();
$('#sped').html(customLink);
}
#customHTML {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<th scope="row">Cart:</th>
<td>
<p id="top_cart_button"><span>€ 199,00</span></p>
</td>
</tr>
<tr class="price">
<th scope="row">Price:</th>
<td data-label="">
<h3 class="mainPrice"><span class="mainPriceAmount">99,00</span></h3>
</td>
</tr>
<tr id="customHTML" style="display:none">
<th scope="row">Shipping:</th>
<td>
<p id="sped"></p>
</td>
</tr>
</table>
span is not a class but an element, this works:
parseInt($('#top_cart_button span').text(), 10);
<li id="top_cart_button">
<a href="default.asp?cmd=showCart" rel="nofollow">
<span>0,00</span>
</a>
</li>
If its necessarily inside an anchor tag. (meaning if you want to ignore other spans that are not inside the "a" tag. )
$("li#top_cart_button a span").text(); //or html() if you are trying to get html.
and same for the function
parseInt($("li#top_cart_button a span").text(), 10);
You're almost nearly there just remove the "." between top_cart_button and span.
$('$('#top_cart_button span')')
Gets the span "element" in top_cart_button whereas your statement has a "." prefix which gets the first element with span "class" name.
function getDigitsFromString(str){
const regex = /\d+[.]?\d+/g;
const result = regex.exec(str.replace(',','.'));
if(result[0] !== null){
return parseFloat(result[0]);
}
return;
}
console.log(getDigitsFromString($('#top_cart_button > a > span').text()));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li id="top_cart_button">
<a href="default.asp?cmd=showCart" rel="nofollow">
<span>€ 55,55</span>
</a>
</li>

How to display table in same page as the button?The tables are already made up in another html file so I’m just pulling them from there

I have 6 links. I would like for when I click on a link that table shows next to it. I need the table to show in same page as link and not replace it. So I need all tables hidden until i click that link.
For the 6 different tables they each have their own .html file I'm pulling them from.
Heres my code:
function show(nr) {
document.getElementById("table1").style.display = "none";
document.getElementById("table2").style.display = "none";
document.getElementById("table3").style.display = "none";
document.getElementById("table4").style.display = "none";
document.getElementById("table5").style.display = "none";
document.getElementById("table6").style.display = "none";
document.getElementById("table" + nr).style.display = "block";
}
td {
vertical-align: center;
}
#table1,
#table2,
#table3,
#table4,
#table5,
#table6 {
display: none;
}
<h1>BV-Line58 Demi</h1>
<br>
<table>
<tr>
<td>
<a href="bv-line58assets.html" name="table1" onclick='show(1); '>Assets</a>
<br><br>
<a href="bv-line58endpoints.html" name="table2" onclick='show(2);'>Endpoints</a>
<br><br>
<a href="#" name="table3" onclick='show(3);'>IP Search</a>
<br><br>
<a href="#" name="table4" onclick='show(4);'>Non-Malicious Alerts</a>
<br><br>
<a href="bv-line58routes.html" name="table5" onclick='show(5);'>Routes</a>
<br><br>
<a href="#" name="table6" onclick='show(6);'>Suricata Alerts</a>
</td>
<td>
</td>
<td>
<div id="table1"></div>
<div id="table2"></div>
<div id="table3"></div>
<div id="table4"></div>
<div id="table5"></div>
<div id="table6"></div>
</td>
</tr>
</table>
If your need is only to show the tables from a given html page, you can use iframe. That option relies on the fact that you pages are hosted somewhere so you can link to them.
For example:
<iframe width="560" height="315" src="https://www.your-domain.com/bv-line58assets.html" frameborder="0"></iframe>
In your code
<table>
<tr>
<td>
<a href="javascript:void(0)" name="table1" onclick='show(1);>Assets</a>
</td>
<td>
</td>
<td>
<div id="table1">
<iframe width="560" height="315" src="https://www.your-domain.com/bv-line58assets.html" frameborder="0"></iframe>
</div>
</td>
</tr>
</table>
Once each div contains its corresponding iframe, your show(nr) function will show the relevant div, and therefor the relevant iframe (which holds the table, as much as I understand).
Note: this approach is not very comfortable if you actually need to access the data inside the iframe, but for view purposes it should be fine.
There are better ways to handle this, especially if you use a client-side framework like angular or react. This should be a fast and simple way to go with, especially if your tables are not a part of this application (which I am not sure about, as you didn't mention it clearly)
I hope this helps.

Getting the HTML of a DIV with another element

I have a bunch of thumbnails. Of these I know the link in my JQuery script - however, I need to get the HTML from the .caption, and I just can't make it do that.
I've tried the following things
$('a.thumbnail').click(function() {
$(this).closest('.caption').html()
$(this).find('.caption').html()
$(this).children('.caption').html()
});
Here's the HTML:
<div class="thumbnail">
<a href="#" class="thumbnail">
<img src="{{ URL::asset($item->image) }}" alt="">
</a>
<div class="caption" align="center">
{{ $item->name }}
</div>
</div>
This would also work, since the .caption is a sibling of your a:
$('a.thumbnail').click(function() {
$(this).siblings('.caption').html();
});
Why yours don't work:
$(this).closest('.caption').html() // .caption is not an ancestor of the a
$(this).find('.caption').html() // .caption is not a descendant of the a
$(this).children('.caption').html() // .caption is not a child of the a
Try:
$('a.thumbnail').click(function() {
$(this).closest('div.thumbnail').find('.caption').html();
});
jsFiddle example
When you click the image, you need to use .closest() to traverse up to the containing div, and the use find to go back down to .find() the caption.
You could try:
$(this).parent().find('.caption').html();
Try this:
$(".caption").text();
or Perhaps
$(".thumbnail").find(".caption").text();
Although these might give you the entire class. Have thought about adding ids?
I've done this before using the Razor engine:
#foreach (var temp in ListOfStuffWithIds)
{
<tr class="class" >
<td class="tdClass" >
<input id="#temp.Id" type="checkbox" /></td>
<td class="tdClass2">#temp.Id</td>
<td>#temp.Name</td>
</tr>
}

How to add div to span inside this table row?

I have a table row as such:
<tr class="song-row song-row-selected" data-id="1">
<td data-col="title">
<span class="song-content">
<img src="img/cover3.jpg" />
Song Title
</span>
</td>
<td>3:37</td>
<td>song artist</td>
<td>song album</td>
<td>23</td>
</tr>
I want to add a div to indicate that the song is paused (surrounded by *):
<tr class="song-row song-row-selected" data-id="1">
<td data-col="title">
<span class="song-content">
<img src="img/cover3.jpg" />
Song Title
*<div class="song-indicator loading"></div>*
</span>
</td>
<td>3:37</td>
<td>song artist</td>
<td>song album</td>
<td>23</td>
</tr>
I was hoping to use JQuery. So far I have:
function displayPause() {
$('tr.song-row.song-row-selected:first').each(function() {
$(this).siblings('td span.song-content').add('<div class="song-indicator paused"></div>');
});
}
Needless to say, it doesn't add the div. Also, I would like a function for me to easily remove the div from the span. Does anyone know where to point me in the right direction?
You should be using append as well as children, not siblings
$(this).children('td span.song-content').append('<div class="song-indicator paused"></div><input type="button" class="removeDiv" value="Remove"/>');
I also added a button right next to your div, clicking this will remove that div with this code:
$(document).on("click", ".removeDir", function() {
$(this).prev(".song-indicator").remove();
$(this).remove();
});
append is what you want:
$(this).find('td span.song-content')
.append('<div class="song-indicator paused"></div>');
This will ... append the div to the end of your span.
Also, as tymeJV says, your td is not a sibling of your tr; it's a child. Use either children, or find to grab it.
And to remove it, you'd use remove. If I understand your app correctly, it should be something like this:
$('tr.song-row.song-row-selected:first')
.find("div.song-indicator.paused").remove();
Here a litte sample on jsfiddle
$("tr.song-row-selected:first td span.song-content").append("*<div class='song-indicator loading'></div>*");

javascript: access elements within a table

I'm pretty new to javascript. I have this sample table. I want to be able to get the "http://www.msn.com" but haven't been able to do so. How should I do this?
thanx in advance
j
<body>
<div id="tableContainer">
<table width="100%">
<thead>
<tr>
<th width="16%" > </th >
<th width="62%"> Otras acciones</th >
<th class="sort" width="2%"> Código certificado</th>
<th class="sort" > Descripción</th>
</tr>
</thead>
<tbody>
<tr>
<td class="iconos" >
<span class="sigAccion">
<a href="#" class="sigIcnHref" title="Duplicar" />
<span class=" btnDuplicar">
</span></a>
<a href="http://www.msn.com" class="sigIcnHref" title="Modificar" />
<span class=" btnModificar">
</span></a>
</span> </td>
<td class="AccionRegistro">
<ul>
<li>
<a href="#" >Docència </a></li>
<li>
<a href="#" >Matrícula(S) </a></li>
<li>
<a href="#" >Plans(1) </a></li>
<li>
<a href="#" >Professors(1) </a></li>
<li>
<a href="#" >Horaris(9) </a></li>
<li>
<a href="#" >HorarisProfessors(1) </a></li>
</ul></td>
<td > <sup>2</sup>CAMD</td>
<td> Cert. Alumno Matriculado Ext.</td>
</tr>
</tbody>
</table>
</div>
</body>
straight javascript is pretty easy.
grab a reference to a known element above the a element higher up the tree
get a list of a elements under the known element
match the href property to the value you know
var anchor = null;
var container;
var items;
container = document.getElementById('tableContainer');
items = container.getElementsByTagName('a');
for (var j = 0; j < items.length; j++) {
if (items[j].href === 'http://www.msn.com') {
anchor = items[j];
break;
}
}
it would be better if you could directly reference the table element and then get a list of a elements from there, but if that's the only table in tableContainer it's fine.
for checking the href property for a known value, i usually go with a case-insensitive regex but this should be fine for your case.
Using a framework like jQuery it's pretty simple:
var href = $('#tableContainer .iconos a[title=Modificar]').attr('href');
Using plain Javascript it's more complicated if you can't simply add an id to the element to make it easier to locate it. You can for example look through all links in the page:
var href;
var links = document.links;
for (var i = 0; i < links.length; i++) {
if (links[i].title == 'Modificar') href = links[i].href;
}
you can also do this by using jQuery
$('#tableContainer a').each(function() {
if (this.href == 'http://www.msn.com'){
// Do something like $(this).hide();
}
else {
// Do somthing like $(this).show();
}
});
here is an example of JSFiddle
If the structure is always like this, a code for Prototype would look like this:
var allLinks = $$('#tableConatiner tbody tr td span a');
var msnLInk = allLinks[1].href;
You can also use jQuery with a similar selector or even pure JS which will need some additional selections. But using an id attribute (e.g. "msnLink") you can get it using a direct selection:
var msnLink = $('msnLink').href;
I can you extend the code with an ID?
EDIT: If the title or class is unique and always the same you can also use one of the following lines:
var msnLink = $$('a[class="sigIcnHref"]').first().href;
var msnLink = $$('a[title="Modificar"]').first().href;
Can you give us some more information about the structure and what you want to do with the element after selecting it?

Categories