I want to get element attribute value which belongs to other html page.
For example if I am in file a.html and want to get 开发者_开发百科data like element attribute value from b.html in a.html
All I am trying to do in jquery.
Please suggest!
I read posts but I want like below-
something like->
[Code of a.html]var result = get(b.html).getTag(img).getAttribute(src)//not getting exactly
$("#id").append(result)
any idea how can i achieve this?
first you will have to fetch the b.html
and then you can find the attribute value e.g.
//if you dont want to display the data make the div hidden
^
$("#someDivID").load("b.html",function(data){
var value=$(data).find("#elementID").attr("attributeName");
});
With jQuery you can load only parts of remote pages. Basic syntax:
$('#result').load('ajax/test.html #container');
The second part of the string is a basic jQuery selector. See the jQuery documentation.
By default, selectors perform their searches within the DOM starting at the document root.
If you want to pass alternate context, you can pass to the optional second parameter to the $() function. For eg,
$('#name', window.parent.frames[0].document).attr();
Keep in mind that you can usually only make direct connections (like with $(..).load(
) to pages on the same domain you're currently on, or to domains that do not have CORS restrictions. (The vast majority of sites have CORS restrictions). If you want to load the content from a cross-domain page that has CORS restrictions, you'll have to make make the request through your server, and have your server make the request to the other site, then respond to your front-end script with the response.
As for this question, if you want to achieve this result without jQuery, you can use DOMParser on the response text instead, to transform it into a document, and then you can use DOM methods on that document to retrieve the element, parse it as desired, and insert it (or data retrieved from it) onto the current page. For example:
fetch('b.html') // replace with the URL of the external page
.then(res => res.text())
.then((responseText) => {
const doc = new DOMParser().parseFromString(responseText, 'text/html');
const targetElementOnOtherPage = doc.querySelector('img');
const src = targetElementOnOtherPage.src;
document.querySelector('#id').insertAdjacentHTML('beforeend', `<img src="${src}">`);
})
.catch((err) => {
// There was an error, handle it here
});
精彩评论