I am fetching URL content via Ajax. In the text, I have to find the tag containing "See Additional", if found, mark all HTML after it with a certain class, for instance .REMOVE. I am unable to extract the irrelevant DOM but I am unable disassociate with the rest of the HTML. I also tried remove() but I am unable to fetch the remaining HTML. Below is my code:
$( document ).ready(function() {
$.get("http://localhost:8000/read.php", function(data, status){
html = $.parseHTML( data ) // Construct DOM from string
//Check if it exist, remove/isolate it
see_additional = $(html).find("H2:contains('See Additional')");
if(see_additional.length > 0) {
console.log('Found it')
parent = see_additional.parent()
$(parent).addClass('remove')
//parent.remove();
//console.log(parent.html())
$('#view').html($(html).html()) // The HTML here is NOT showing entire HTML without removed parent DOM
}
});
});
End Goal
Basically, I have to count the number of links on a page but it should ignore links that are found in HTML after H1/H2 Tags contain "See Additional.."
Related
I have HTML page that has Ajax call to load table content
<html>
....
<script sec:haspermission="VIEW_NOTE" th:inline='javascript'>
require(['app/agent/viewGlobalAgent'], function (){
var individualId= [[${model.agent.individual.id}]];
var agentId= [[${model.agent.id}]];
$.get("/notes/referenceTable.html?individualId="+individualId+"&agentId="+agentId, function(data){
console.log("theData " , data);
var noteList = $("#note-list-container2").value;
var fileList = $("#file-list-container2").value;
// document.getElementById("note-list-container").innerHTML = noteList;
// document.getElementById("note-file-form").innerHTML = fileList;
$("#note-list-container").html(noteList);
$("#note-file-form").html(fileList);
});
</script>
....
</html>
the html that Ajax call load
<div>
<div id="note-list-container2">
....
</div>
<div id="file-list-container2">
....
</div>
</div>
I need to access these two div on callback of Ajax call
$.get("/notes/referenceTable.html?individualId="+individualId+"&agentId="+agentId, function(data){
I tried to access them but its not working
$("#note-list-container2").value
is any way to access div in loaded html
Since you want content from within the new html returned as data you want to wrap that data in $() and query within that object
Then use text() or html() since value is only for form controls, not content elements
$.get(url, function(data) {
var $data = $(data);
var noteList = $data.find("#note-list-container2").text();// or html()
var fileList = $data.find("#file-list-container2").text();
$("#note-list-container").html(noteList);
$("#note-file-form").html(fileList);
});
jQuery.text(): Get the combined text contents of each element in
the set of matched elements, including their descendants, or set the
text contents of the matched elements
jQuery.val(): Get the current value of the first element in the
set of matched elements or set the value of every matched element.
The .val() method is primarily used to get the values of form elements
such as input, select and textarea. When called on an empty
collection, it returns undefined.
A div element does not have a value....
An example:
console.log('text(): ' + $("#note-list-container2").text());
console.log('val(): ' + $("#note-list-container2").val());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="note-list-container2">
....
</div>
I’m guessing you’re using jQuery. The HTML contents can be accessed with .html() not with value. There is no value attribute on a div element. More importantly, you should attempt to get the contents of the element AFTER updating it, not before. Also, the selectors should match. From your example, it seems that you're attempting to get the contents for a #note-list-container2 but you're updating a #note-list-container element. One of those IDs is wrong, given your sample AJAX call output.
I am learning javascript and trying to build a chat app like intercom.
How do i go about creating a popup on another page once my js script is planted??
I do it locally like so:
function Hide()
{
document.getElementById('div1').style.visibility="hidden";
}
There is many way to do it i'll explain the idea with some examples, let's go
Our code based on two functionalities:
1: innerHtml = "<YOUR CODE/>"; This property is for injecting the html in the element more info.
2: document.getElementById("IdName") This property is for selecting and element wich we will apply some functionalities, in our case is the property N°1 more info.
3: <div id="IdName"></div> Here where we will append our html or text more info.
Now we start with some examples:
1st example:
API File:
function function_name(argument) {
document.getElementById(argument).innerHTML = "<p>Paragraph example..</p>";
}
User File:
// first of all the user need to put a div with an attribute ID in his html where
//he want to append the html given by the API
<div id="IdName"></div>
//after that he must call the specified function wich is in our case function_name() and put the ID as argument
function_name("IdName"); // this will append the html in the div with the ID == IdName
Also you can use document.getElementsByClassName("className"); in place of ID
2nd example:
In this case the user don't need to put any additional html or any other things; in this example we will add our html into the body element wich is a necessary element in HTML page.
document.body.innerHTML += "<p>Paragraph example..</p>";
I am getting an HTML string in response to an ajax request. It is a large HTML string with a lot of hierarchical child nodes.
I parse it using
jQuery.parseHTML();
to convert it into a DOM. Now i want to change the content of a child node with a certain ID and then regenerate the HTML.
The Problem is when ever i use a jQuery method to select a dom element to make the changes, it returns that particular node and the
jQuery.html()
just changes that node to HTML.
I have tried following code samples
var parsedHTML = jQuery.parseHTML( 'htmlstring' );
jQuery(parsedHTML).find('#element-id').text('changed text').html();
or
jQuery(parsedHTML).filter('#element-id').text('changed text').html();
the problem is it only returns span#element-id and when html() is applied, the generated html has only span text.
How can i generate back the complete html and change the specific node?
Don't chain (or if you do, use end, but simpler really just not to). By chaining, you're saying you only want the HTML of the last set of elements in the chain:
var elements = jQuery(parsedHTML);
elements.filter('#element-id').text('changed text');
var html = elements.html();
But elements.html() will only give you the inner HTML of the first element. To get the full HTML string again, you need to get the outer HTML of each element and join them together:
var html = elements.map(function() {
return this.outerHTML;
}).get().join("");
Note that your use of filter assumes the element is at the top level of the HTML string. If it is, great, that's fine. If it isn't, you'll want find instead.
Example with filter:
var parsedHTML = jQuery.parseHTML(
"<span>no change</span>" +
"<span id='element-id'>change me</span>" +
"<span>no change</span>"
);
var elements = jQuery(parsedHTML);
elements.filter('#element-id').text('changed text');
console.log(elements.map(function() {
return this.outerHTML;
}).get().join(""));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Example with find:
var parsedHTML = jQuery.parseHTML(
"<span>no change</span>" +
"<div>the span is in here<span id='element-id'>change me</span></div>" +
"<span>no change</span>"
);
var elements = jQuery(parsedHTML);
elements.find('#element-id').text('changed text');
console.log(elements.map(function() {
return this.outerHTML;
}).get().join(""));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I "learned" JavaScript a few months ago but quickly picked up Python and spent the past few months writing programs in that language, so I decided it would be a good idea to go back and actually learn JavaScript. Right now I'm making a very simple "blog" with JS that takes the title of the post, generates a hash link from the post, and creates a recent posts section where you can click the link to jump to the post in the page.
For instance, say one of the posts is formatted like this:
<h2 class="post">Another post for you</h2>
<h4>I know you love these</h4>
With multiple posts, and an empty container at the bottom, which will be used to append the recent posts links:
<div id="get-post"></div>
My JS code basically grabs each title with the post class and creates a hash link from the element's title (removing spaces and commas). It then creates and appends a text node consisting of the post title, and then appends the entire link into the get-post container.
var postList = $('#get-post');
var post = $('.post');
function generateRecentPosts() {
post.each(function() {
// Create link from post title that will be used to
// access that post.
var postLink = document.createElement('a');
// Create text node from post title that will be appended
// to the postLink.
var text = document.createTextNode($(this).html());
// Add elements to the DOM.
postLink.href = createLocalLink($(this));
postLink.appendChild(text);
postList.append(postLink);
postList.append('<br />');
});
}
function createLocalLink(elm) {
// Creates the href link that will be used to go to a blog post.
// For example, if the title of the elm parameter is "My Post",
// a link is created called #My-Post that will be used to access
// that post.
elm.id = elm.html().replace(/,/g, '').replace(/\s/g, '-');
console.log(elm.id); // Make sure the ID is added.
return '#' + elm.id;
}
generateRecentPosts();
My problem is that the links it generates to not point to the ID created for each title. When I click on the link, I can see that it successfully created the href hash #My-Post and added it to the anchor tag, but it doesn't take me to the post title.
Example: http://jsfiddle.net/samrap/GQtxL/
I even added a console log function to make sure the ID is being added to the title as I thought that was the problem, but it isn't because the console is printing the correct new ID. I could really use some help in figuring out where exactly the problem is here.
Your h2 tags need to have an id or name attribute that corresponds with the link, that is what makes internal links work. The id is not getting added because you are accessing a jQuery object as if it were a DOM node (elm.id = ...). Modify your createLocalLink function to use jQuery's attr method to set the id property:
elm.attr('id', elm.html().replace(/,/g, '').replace(/\s/g, '-'));
Additionally, since you have jQuery available you could whittle your code down to:
var $this = $(this),
link = createLocalLink($this);
var $postLink = $('a', {
text: $this.text(),
href: link
})
postList.append($postLink).append('<br />');
Here is your fiddle updated: http://jsfiddle.net/GQtxL/1/
This is because your link uses the href = "#My-Post" but none of the posts has the ID "My-Post". It only has a class "post".
This happens because the argument that your are passing to the createLocalLink() function is a DOM Node. But by doing elm.id you are not changing the DOM property but adding another property to the "elm" object. Thus your "elm" object is
x.fn.x.init[1]
0: h2.post
context: h2.post
id: "Another-post-for-you"
length: 1
__proto__: Object[0]
Thus the actual post never gets the attribute ID only "elm" object gets it. Note the empty ID attribute below
draggable: false
firstChild: text
firstElementChild: null
hidden: false
id: ""
innerHTML: "Another post for you"
innerText: "Another post for you"
Thus your document has no element with the ID "My-Post". You can view the source of your HTML to verify this.
For internal links to work there should be an element with the same ID as that used in the href attribute of the link.
For example
<div id="post1">
Your Post Here
</div>
<!--just to show the effect of moving to the post-->
<div style="clear:both; height:900px"></div>
Click Here
This would work because there is an element with the id "post1" and the link uses the href "#post1" which links it to the corresponding element. Hence, add the corresponding id to your post as well (other than your link) for it to work.
In function createLocalLink you are using elm argument as dom node, but actually passing a jQuery wrapped object to it, which don't have id property. To get it work, use elm.get(0).id = ... or elm.attr('id', elm.text().replace(/,/g, '').replace(/\s/g, '-'););
Problem:
Extract all html between two headers including the headers html. The header text is known, but not the formatting, tag name, etc. They are not within the same parent and might (well, almost for sure) have sub children within it's own children).
To clarify: headers could be inside a <h1> or <div> or any other tag. They may also be surrounded by <b>, <i>, <font> or more <div> tags. The key is: the only text within the element is the header text.
The tools I have available are: C# 3.0 utilizing a WebBrowser control, or Jquery/Js.
I've taken the Jquery route, traversing the DOM, but I've ran into the issue of children and adding them appropriately. Here is the code so far:
function getAllBetween(firstEl,lastEl) {
var collection = new Array(); // Collection of Elements
var fefound =false;
$('body').find('*').each(function(){
var curEl = $(this);
if($(curEl).text() == firstEl)
fefound=true;
if($(curEl).text() == lastEl)
return false;
// need something to add children children
// otherwise we get <table></table><tbody></tbody><tr></tr> etc
if (fefound)
collection.push(curEl);
});
var div = document.createElement("DIV");
for (var i=0,len=collection.length;i<len;i++){
$(div).append(collection[i]);
}
return($(div).html());
}
Should I be continueing down this road? With some sort of recursive function checking/handling children, or would a whole new approach be better suited?
For the sake of testing, here is some sample markup:
<body>
<div>
<div>Start</div>
<table><tbody><tr><td>Oops</td></tr></tbody></table>
</div>
<div>
<div>End</div>
</div>
</body>
Any suggestions or thoughts are greatly appreciated!
My thought is a regex, something along the lines of
.*<(?<tag>.+)>Start</\1>(?<found_data>.+)<\1>End</\1>.*
should get you everything between the Start and end div tags.
Here's an idea:
$(function() {
// Get the parent div start is in:
var $elie = $("div:contains(Start)").eq(0), htmlArr = [];
// Push HTML of that div to the HTML array
htmlArr.push($('<div>').append( $elie.clone() ).html());
// Keep moving along and adding to array until we hit END
while($elie.find("div:contains(End)").length != 1) {
$elie = $elie.next();
htmlArr.push($('<div>').append( $elie.clone() ).html());
};
// htmlArr now has the HTML
// let's see what it is:
alert(htmlArr.join(""));
});
Try it out with this jsFiddle example
This takes the entire parent div that start is in. I'm not sure that's what you want though. The outerHTML is done by $('<div>').append( element.clone() ).html(), since outerHTML support is not cross browser yet. All the html is stored in an array, you could also just store the elements in the array.