/    Sign up×
Community /Pin to ProfileBookmark

get Elements By Id

I am trying to import some text from one page on my website to be used in another. I have tried to use getElementsById / getElementsByTagName and I am ending up with empty variables.

[CODE]
<script type=”text/javascript”>

var pageLoc = “http://niche.uwo.ca/rsstest1”;

var myContent = pageLoc.getElementsById(“rss1”);
document.write(myContent);

var myContent2 = pageLoc.getElementsByTagName(“p”);
document.write(myContent2);
</script>
[/CODE]

Neither of the two have worked. Can anyone tell me what I am doing wrong?

Thank you very much.

Adam

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@CuppyTeaNov 28.2008 — document.getElementById

getElementById returns 1 element, not many (hence the non-plural);

You will be getting a blank result on the 2nd statement, as you are writing nothing over the page with the 1st statement.

However, with both of your document.writes, you will be writing objects/ arrays.

document.getElementById will return the object of the element with the specified Id. So to display sometihng useful, you will need to do something like.... document.write(myContent.id), or document.write(myContent.innerHTML).

document.getElementsByTagName will return an array of objects, so you will need to do something like .... document.write(myContent[0].id) or document.write(myContent[0].innerHTML) (you should also check that myContent.length > 0 before doing this, to prevent errors).

Furthermore, you cannot simply load the page contents into a variable using var something = "http://google.co.uk". The variable "something" will now be a string equal to "http://google.co.uk" - not the contents of that page. To get the contents of the page, you will need to use AJAX.
×

Success!

Help @acrymble spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.20,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...