How to find next element of particular style after specific button? - javascript

I use the following code currently to read data from the first column of the first table:
jQuery(".confluenceTable tr:gt(0) td:nth-child(1)").each(function() {
projects_list.push(jQuery(this).text().trim());
});
Now I need to work with the first table of .confluenceTable located after button with #showdata id. How should I do it?
I tried something like
jQuery("#showdata").nextAll(".confluenceTable tr:gt(0) td:nth-child(1)").each(function() {
but it returns no result.
The html looks like below
<button name="showdata" id="showdata" type="button"><p>show data</p></button>
<p>some text</p>
<div class="table-wrap">
<table class="wrapped relative-table confluenceTable" style="width: 99.94%;">

First, when posting questions which are strongly related to dom querying and manipulation, please include well structured code, you should not make people go jumping unnecessary obstacles to help you.
As for the problem at hand, the main thing missing was :first.
The first snippet is in case the table will be INSIDE <div class="table-wrap"></div>, else the second snippet.
var res = $('#showdata').nextAll('.table-wrap:first').children('.confluenceTable');
var projects_list=[];
res.find("tr:gt(0) td:nth-child(1)").each(function() {
projects_list.push(jQuery(this).text().trim());
});
console.log(projects_list);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button name="showdata" id="showdata" type="button"><p>show data</p></button>
<p>some text</p>
<div class="table-wrap">
<table class="wrapped relative-table confluenceTable" style="width: 99.94%;">
<thead><tr><th>header1</th><th>header2</th></tr></thead>
<tbody><tr><td>cell1</td><td>cell2</td></tr>
<tr><td>cell3</td><td>cell4</td></tr>
<tr><td>cell5</td><td>cell6</td></tr></tbody>
</table>
</div>
var res = $('#showdata').nextAll('.confluenceTable:first');
var projects_list=[];
res.find("tr:gt(0) td:nth-child(1)").each(function() {
projects_list.push(jQuery(this).text().trim());
});
console.log(projects_list);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button name="showdata" id="showdata" type="button"><p>show data</p></button>
<p>some text</p>
<div class="table-wrap">
</div>
<table class="wrapped relative-table confluenceTable" style="width: 99.94%;">
<thead><tr><th>header1</th><th>header2</th></tr></thead>
<tbody><tr><td>cell1</td><td>cell2</td></tr>
<tr><td>cell3</td><td>cell4</td></tr>
<tr><td>cell5</td><td>cell6</td></tr></tbody>
</table>

Related

How to get original HTML back after it was changed

I am trying to get the original heading text to display after it was changed by jQuery, without having to write in both the markup and in the script.
My html starts with:
<div class="headings">
<h1>Original Heading</h1>
</div>
Then after a user makes their selection, the heading is changed with jQuery:
$('#userSelection').on('click', function() {
$('.headings h1').html('<h1>New Heading</h1>');
});
Currently I have it set so if a user clicks the reset button, the heading is changed back to the original with jQuery:
$('#resetBtn').on('click', function() {
$('.headings h1').html('<h1>Original Heading</h1>');
});
Is there a way to get back to the original heading without having to write it out in jQuery, since it's already in the original HTML?
Only way to get it back is to refresh the page, or once again write it back with jQuery.
Your current method inserts another <h1> into the existing <h1> which may not be what you're after. This first snippet demonstrates that. The nested <h1>'s appears to be what causes the font-size to increase when clicking. Interesting...
$('#userSelection').on('click', function() {
$('.headings h1').html('<h1>New Heading</h1>');
});
$('#resetBtn').on('click', function() {
$('.headings h1').html('<h1>Original Heading</h1>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="headings">
<h1>Original Heading</h1>
</div>
<div>
<input type="button" id="userSelection" value="userSelection">
<input type="button" id="resetBtn" value="resetBtn">
</div>
The second snippet shows using .empty().append() which does not cause nested <h1>'s.
$('#userSelection').on('click', function() {
$('.headings').empty().append('<h1>New Heading</h1>');
});
$('#resetBtn').on('click', function() {
$('.headings').empty().append('<h1>Original Heading</h1>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="headings">
<h1>Original Heading</h1>
</div>
<div>
<input type="button" id="userSelection" value="userSelection">
<input type="button" id="resetBtn" value="resetBtn">
</div>
$(document).ready(function() {
var tempBucket = '';//temporary bucket to save our original
//if use localstorage can be like this one
// var tempBucket = localStorage.getItem('original') ?? '';
$('#selectBtn').click(function(){
tempBucket = $('.headings h1').html();
//if using localstorage
//localStorage.setItem('original', $('.headings h1').html());
$('.headings h1').html('New Headings');
});
$('#resetBtn').click(function(){
$('.headings h1').html(tempBucket);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="headings">
<h1>Original Heading</h1>
</div>
<button id="selectBtn">select</button>
<button id="resetBtn">reset</button>
Hopefully can answer your question

How do I replace instances of a word in multiple tags on page load?

Trying to replace a word that possibly will come in a foreach loop of a database items in razor view.
What I've tried so far
<section class="section bg-gray">
<div class="container">
<div class="row gap-y">
#foreach (var item in Model)
{
<div class="col-md-6 col-lg-4">
<div class="card d-block">
<p class="text-justify">#item.Text</p>
<p class="text-center mt-7">
<a class="btn btn-primary" href="#">Read more</a>
</p>
</div>
</div>
}
</div>
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var elements = getElementsByClassName("text-justify");
$(elements).each(function(element) {
element.innerHTML = element.innerHTML.replace(/wordToReplace/g, 'newWord');
});
});
</script>
</div>
</section>
Excuse my poor JavaScript, I'm new on front-end. I looked for similar questions but closer topics are usually about replacing instances of a word in one tag. Please help.
You don't need jQuery for this - you can use document.querySelectorAll and just replace the desired text of the elements that match the selector.
Note that I have dodgied up a text element and for the desired class and replacing justify with justified to demonstrate the usage.
let elements = document.querySelectorAll(".text-justify");
elements.forEach(function(element){
let textContent = element.innerText;
let newTextContent = textContent.replace(/justify/g, 'justified');
element.innerText = newTextContent;
})
<p class="text-justify">This is a text with the class of text-justify</p>
<p>This is a text without the class of text-justify</p>
<p class="text-justify">This is a text with the class of text-justify</p>
You don't need jQuery for this - use a simple forEach loop. I've also refactored some other parts of your code (eg you were missing document:
document.getElementsByClassName("text-justify").forEach(element => element.innerHTML = element.innerHTML.replace(/word/g, "newWord"));
But if you really want to use jQuery:
$(".text-justify").html((index, element) => element.replace(/word/g, "newWord"));

jQuery select another element with certain class in same parent

let say i have this div
<div id='parent'>
<button id='button'></button>
<div id='child'>
<div id='grandchild' class='lookAtMe'>
Some JSON text
</div>
</div>
</div>
I wanted to give the #button an on click event that returned the text at #lookAtMe div, specific to the div whom it shares parent/grandparent (in this case, the #parent div)
I tried using:
$("#button").on("click",function(){
var ReturnedText = $(this).parent(".lookAtMe").text();
console.log(RetrunedText);
});
But the console log would retruned (empty string).
Where did i do wrong? please help. Thankyou very much.
Because there is n o parent with that class. You need find().
Actually you need to write
var ReturnedText = $(this).parent().find(".lookAtMe").text();
$("#button").on("click",function(){
var ReturnedText = $(this).parent().find(".lookAtMe").text();
console.log(ReturnedText);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='parent'>
<button id='button'></button>
<div id='child'>
<div id='grandchild' class='lookAtMe'>
Some JSON text
</div>
</div>
</div>

Setting Width of <div> with Javascript

I have a <table> which is dynamically created so the width is unknown. I'm trying to add horizontal scroll bars to the top and bottom of it. My current code...
<div class="wrapper1">
<div class="div1" width="<script type=\"text/javascript\">document.write(mytext);</script>">
</div>
</div>
<div class="wrapper2">
<div class="div2">
<table id="table_width">
*table content goes here*
</table>
</div>
</div>
<script type="text/javascript">
$(function(){
$(".wrapper1").scroll(function(){
$(".wrapper2")
.scrollLeft($(".wrapper1").scrollLeft());
});
$(".wrapper2").scroll(function(){
$(".wrapper1")
.scrollLeft($(".wrapper2").scrollLeft());
});
});
var mytext = document.getElementById("table_width").offsetWidth; //Method 1
var mytext = document.getElementById("table_width").style.width = width + 'px'; //Method 2
</script>
In the last few lines, I've tried two different methods to set the width of the containing <div> to be mytext.
Any ideas why either method isn't working? BTW, I'm not trying both methods at the same time the way it's shown here.
To find the width of an element you need to use window.getComputedStyle followed by getPropertyValue on that returned value. What you are doing now only gives you the CSS value which is not set.
https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle
The problem could be this.
The script you have written to find mytext is being executed after the table is created. But by the time the div is created value of mytext is not known. So I would recommend doing this.
<!DOCTYPE html>
<div class="wrapper1">
<div id="div1">
</div>
</div>
<div class="wrapper2">
<div class="div2">
<table>
*table content goes here*
</table>
</div>
<script type="text/javascript">
$(function(){
$(".wrapper1").scroll(function(){
$(".wrapper2")
.scrollLeft($(".wrapper1").scrollLeft());
});
$(".wrapper2").scroll(function(){
$(".wrapper1")
.scrollLeft($(".wrapper2").scrollLeft());
});
});
var mytext = document.getElementById("table_width").offsetWidth; //Method 1
var mytext = document.getElementById("table_width").style.width ; //Method 2
document.getElementById('div1').width = mytext;
</script>
</html>
The above code changes the width of the div after finding the value of mytext.
I ended up using parts of both of the suggested answers for this question. After a lot of fiddling, I ended up with this for the final Javascript...
var elem = document.getElementById("table_width");
var mytext = window.getComputedStyle(elem,null).getPropertyValue("width");
$('#div1').css({'width':mytext});
$('#div1').css({'overflow': 'scroll'});

How to replace text inside IDless <span> with javascript?

I have some text inside <span></span> tags and I want to change that text to something else when page is loaded.
So lets say default text is 'Story' (outputted by some CMS system and I can't edit it). So when page is loaded, .js detects that 'Story' word and replaces it with 'View This Story'.
Is that possible somehow?
Cheers
Update: I did search before asking and none of those methods I found works. Like I said the text is outputted by CMS and it gives wrong title, the title itself cannot be edited via CMS because it is used for other terms and tagging which is correct, so I was looking for js workaround to rename it on page load.
And span has no ID and I cannot give it any ID, because like I said it works as designed by CMS.
<div class="views-row views-row-1 views-row-odd views-row-first active">
<div class="views-field views-field-name">
<span class="field-content">Story</span>
</div>
</div>
<div class="views-row views-row-2 views-row-even">
<div class="views-field views-field-name">
<span class="field-content">Second Story</span>
</div>
</div>
As you can see spans do not have IDs, but repeating classes only.
UPDATED as per OP request
You can replace any text within spans. You could even use regular expressions to make it more flexible, but let's leave this for now:
Native Javascript
var lookupSpanAndReplace = function(textFrom, textTo) {
var spans = document.getElementsByTagName('span');
for (i=0; i<spans.length; i++)
if (spans[i].innerHTML.indexOf(textFrom) >= 0)
spans[i].innerHTML = mySpan.innerHTML.replace(textFrom, textTo);
}
lookupSpanAndReplace("Story", "My New Text");
jQuery
var lookupSpanAndReplace = function(textFrom, textTo) {
$('span:contains(' + textFrom + ')').each(function(index, element) {
$(element).text($(element).text().replace(textFrom, textTo));
});
}
lookupSpanAndReplace("Story", "My New Text");
Try
$('#spanID').text("View This Story");
or if you want to replace a part of text
$('#spanID').text(function () {
return this.innerHTML.replace('Story', 'View This Story');
});
Give you span an ID and then run text([your new text]) on that node:
HTML
<span id="mySpan">Story</span>
jQuery
$('#mySpan').text("View This Story");
JSFiddle with jQuery
Or you can do it without jQuery:
document.getElementById("mySpan").innerHTML = "View This Story";
JSFiddle with plain 'ol Javascript
<script>
function changeSpan(){
var spans = document.getElementsByTagName ("span");
for (i = 0; i < spams.length; i++){
spans[i].innerHTML = textThatYouWant ();
}
}
</script>
<head onload="changeSpan()" >
<tile> ... </title>
</head>
<body>
...
</body>
Use the following to solve the issue.
HTML code:
<html>
<head>
<script>
function replace_text_span()
{
for(i=0;i<document.getElementsByTagName('span').length;i++)
{
document.getElementsByTagName('span')[i].innerHTML=document.getElementsByTagName('span')[i].innerHTML.replace("Story","View This Story");
}
}
</script>
<style>
</style>
</head>
<body onload="replace_text_span()">
<div class="views-row views-row-1 views-row-odd views-row-first active">
<div class="views-field views-field-name">
<span class="field-content">Story</span>
</div>
</div>
<div class="views-row views-row-2 views-row-even">
<div class="views-field views-field-name">
<span class="field-content">Second Story</span>
</div>
</div>
</body>
</html>

Categories